user.save() doesn't seem to save a specific field that I add to user

Viewed 308

If I use await user.save() in the code below it seems to get stuck but if I use it without await it seems to move ahead and in the response the passwordResetToken is displayed.. However in the database, for some reason, the rest of the fields get saved but passwordResetToken just doesn't get saved.

I am completely lost about what the reason could be.. Any direction on what I should look for would help.

exports.forgotPassword = async function(req, res, next) {

  // 1. Get user based on POST email
  const user = await User.findOne({ email: req.body.email });

  // 2. Generate random token
  user.passwordResetToken = "123456";

  await user.save({ validateBeforeSave: false });

  // 3. Send it back as an email

  //4. Send Response
  res.status(200).json({
    status: "success",
    data: {
      user: user,
    },
  });
};

this is the response


{
    "status": "success",
    "data": {
        "user": {
            "role": "user",
            "_id": "6116aeb70aae0f7c7d8800bc",
            "name": "Jane Doe",
            "email": "jane@doe.com",
            "__v": 0,
            "passwordResetToken": "123456"
        }
    }
}

However the passwordResetToken still doesn't save it to the database although the rest of it does.. I do have the passwordResetToken as a field in the mongoose.Schema

I had not added this section below to my question earlier so I am adding this to help understand where the issue might lie..

This is the userModels.js

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Name is required"],
  },
  email: {
    type: String,
    required: [true, "Email is required"],
    validate: [validator.isEmail, "Please provide valid email"],
    unique: true,
  },
  role: {
    type: String,
    enum: ["admin", "lead-guide", "guide", "user"],
    default: "user",
  },
  photo: String,
  password: {
    type: String,
    minlength: 8,
    required: [true, "Password is required"],
    select: false,
  },
  passwordConfirm: {
    type: String,
    validate: {
      validator: function(el) {
        return el === this.password;
      },
      message:
        "Password confirmation does not match with Password. Please try again",
    },
  },
  passwordChangedAt: Date,
  passwordResetToken: String,
  passwordResetExpires: Date,
});

and here's the line from userRouter.js for this route..

router.route("/forgotPassword").post(authController.forgotPassword);

4 Answers

Maybe you can try with

let user = await User.findOne({ email: req.body.email });

  // 2. Generate random token
  user.passwordResetToken = "123456";

  user = await user.save();

or you can use

const user = await User.findOneAndUpdate({email:req.body.email},{$set:{passwordResetToken:'123456'},{new:true})

new: true will return updated data.

Make sure that the model file contains the passwordResetToken field. Otherwise, it will be ignored.

I wonder if the issue is with the HTTP request, you might want to have http.post not http.put request for your posted question.

I am not sure if you find your own bug, should you delete the question or update it with an answer. But I'll just answer it here just so that someone who does the same mistake as me, can know what could go wrong.

When it seems like something is not getting saved or when you await the save() method and it gets deadlocked, chances are that it's the pre-save middleware..

It might not be obvious to those like me and you might end up trying to fix and replace your "perfect" code while the bug lies elsewhere.. So 2 things to check if something is not getting saved and if await creates an unending response)

1. Check if the pre-save middleware is configured properly

2. Check if the middleware ends with a next()

In my case it was this.. In the code below I had missed out the ! before the this.isModified("password") And so while testing the response would show me the right object but it would never get saved as the pre-save middleware moved to next().

The await deadlock issue was because I did not end the middleware with the next() method.

this is the faulty code

userSchema.pre("save", function(next) {
  if (this.isModified("password") || this.isNew) return next();

  this.passwordChangedAt = Date.now() - 1000;
});

this is the correct code

userSchema.pre("save", function(next) {
  if (!this.isModified("password") || this.isNew) return next();

  this.passwordChangedAt = Date.now() - 1000;
next();
});

Anyways I hope this saves someone out there some time during debugging their code.

Related