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);
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.