猫鼬模式方法返回未定义

时间:2020-10-09 23:31:34

标签: javascript mongodb express mongoose mongoose-schema

我想创建一种使用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); }; 来验证用户密码的方法 这是下面的代码。

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

这是我创建的UserSchema

this.password

在我的架构.pre('save', ..)中使用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); } }; 时,它可以工作,但是当我使用架构方法时显示未定义。 :(

这是该方法的实现

b_arr = b'\\xff\\x02\\x04\\x01\\x00\\x02'

1 个答案:

答案 0 :(得分:1)

guide中说:

声明使用ES6箭头功能(=>)的方法。箭头函数明确阻止绑定this,因此您的方法将无权访问文档...

因此,在这种情况下,您只需要将UserSchema.methods.validatePassword = async (data) => {...更改为UserSchema.methods.validatePassword = async function(data) {...