Why do I get an error when I try to save mongoose model?

Sefi R

I am trying to create controller for resetting user password in Node.JS. The idea is to fetch the user from DB based on reset password token, do some validation update the relevant field and save it back to the DB. However, I get an error when trying to save the updated user ("user.save is not a function"). What might be the reason?

I have a user model defined as follows:

const mongoose = require("mongoose");
const validator = require("validator");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Please enter valid name"],
    maxLength: [30, "Your name cannot exceed 30 characters]"],
  },
  email: {
    type: String,
    required: [true, "Please enter valid email"],
    unique: true,
    validate: [validator.isEmail, "Please enter valid email address"],
  },
  password: {
    type: String,
    requires: [true, "Please enter your password"],
    minLength: [6, "Your password must be at least 6 characters"],
    select: false,
  },
  avatar: {
    public_id: { type: String, required: true },
    url: { type: String, required: true },
  },
  role: { type: String, default: "user" },
  createdAt: { type: Date, default: new Date().now },
  resetPasswordToken: { type: String },
  resetPasswordExpire: { type: Date },
});

userSchema.pre("save", async function (next) {
  if (!this.isModified("password")) {
    next();
  }
  this.password = await bcrypt.hash(this.password, 10);
});

// check password matching
userSchema.methods.isPasswordMatched = async function (inputPassword) {
  return await bcrypt.compare(inputPassword, this.password);
};

// return JSON Web Token
userSchema.methods.getJwtToken = function () {
  return jwt.sign({ id: this.id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRESIN_TIME,
  });
};

// Generate password token
userSchema.methods.getResetPasswordToken = function () {
  // Generate Token
  const resetToken = crypto.randomBytes(20).toString("hex");

  // Hash token
  this.resetPasswordToken = crypto
    .createHash("sha256")
    .update(resetToken)
    .digest("hex");

  // set expired time
  this.resetPasswordExpire = new Date(Date.now() + 30 * 60 * 1000);

  return resetToken;
};

module.exports = mongoose.model("User", userSchema);

When I try to reset user password I try the following:

  // get the user document from db (make sure token and expiration time are valid)
let user = User.findOne({
    resetPasswordToken: resetPasswordToken,
    resetPasswordExpire: { $gt: Date.now() },
  });

// update password
  user.password = req.body.password;
  user.resetPasswordToken = undefined;
  user.resetPasswordExpire = undefined;
  user.save();
  sendToken(user, 200, res);

for some reason I get an error: "errorMsg": "user.save is not a function"

What might be the problem?

SuleymanSah

Probably, user is null or undefined, so you should handle the user null condition. Also findOne and save returns promise, so you need to add await keyword before them.

Also you have a typo in user schema password field, requires should be required .

let user = await User.findOne({
  resetPasswordToken: resetPasswordToken,
  resetPasswordExpire: { $gt: Date.now() },
});

if (user) {
  // update password
  user.password = req.body.password;
  user.resetPasswordToken = undefined;
  user.resetPasswordExpire = undefined;
  await user.save();
  sendToken(user, 200, res);
} else {
  res.status(400).send("No user found");
}

If you get the user null, you need to fix your query in findOne.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why do I get a compilation error when I try to have two methods with the same name and parameter type?

why do i get exception error when i try output array

Why do I get an error for "__CrtGetFileInformationByHandleEx " when I try to compile

Why do I get an "invalid values" error when I try to access the network settings on Eclipse Mars?

Why I get error when I try to create stored procedure?

Why do I get error "Cannot overwrite model once compiled" in Mongoose when I run my test a second time?

Why do I see `503 Backend Error` when I try to get a Cloud Storage service account?

Why do I get an error when I try to add a dependent task to one created by the C plugin?

Why Do I get an error when I try to get tkinter slider value?

Mongoose pre hooks for save and update do not get called when i used a Model.findOneAndUpdate

Why do i get this error when I try to perform some logical operation on dataframes?

Why I am getting an error when i try to save form into quiz model with entity framework?

Why do I get this error in my logcat when I try to post JSON data?

Why I get Unpermitted parameters error when I try to save with HABTM check_box_tag?

Why do I get error when I try to alert the length of the passed array to the function?

Why do I get an error (Notice: Undefined index) when I try to echo a value from my database?

Why do I get a type error in model.predictOnValues when I try the official example of Streaming Kmeans Clustering of Apache Spark?

Why do I get a syntax error when I try to print a nested hash that has keys containing colons?

Why do I get 'undefined' error when I try to read session atrribute from Controller

Why do I get an error message of NoneType object is not callable when I try to call this function?

Why do I get a NoClassDefFound error when I try to save my test plan?

Why I get error when I try to install pyaudio?

Why do I get this error when I try to load the component in VueJS?

Why do i get this error when I try installing autopep8 using pip?

Why I get error when I try to declare local variable?

Why do I get an Error when I try to rename a table after FROM?

Why do I get an error when I try to see my Text using useState?

Why do I get error when try to convert Carbon to DateTime?

Gitlab CI: why do I get an error when I try to define the pages stage?

TOP Ranking

HotTag

Archive