Search code examples
javascriptmongodbexpressmongoosemongoose-schema

mongoose schema method returning undefined


I want to create a method that validates the user's password by using bcrypt.compare() here is the code below.

UserSchema.methods.validatePassword = async (data) => {
  console.log(this.email); // returns undefined
  console.log(this.first_name); // returns undefined
  return await bcrypt.compare(data, this.password);
};

here is the UserSchema I created

const UserSchema = mongoose.Schema(
  {
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
);

when getting this.password in my schema .pre('save', ..) it works but shows undefined when I use schema methods. :(

here is the implementation of the method

const verifySignIn = async (req, res, next) => {
  const { email, password } = req.body;
  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(404).json({
        status: 'failed',
        message: 'User Not found.',
      });
    }
    const isValid = await user.validatePassword(password);
    if (!isValid) {
      return res.status(401).send({
        message: 'Invalid Password!',
        data: {
          user: null,
        },
      });
    }
    next();
  } catch (err) {
    Server.serverError(res, err);
  }
};

Solution

  • In the guide it says:

    Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document ...

    So in this case, you just need to change UserSchema.methods.validatePassword = async (data) => {... to UserSchema.methods.validatePassword = async function(data) {...