【问题标题】:mongoose schema method returning undefined猫鼬模式方法返回未定义
【发布时间】:2021-01-25 00:50:29
【问题描述】:

我想创建一个使用bcrypt.compare() 验证用户密码的方法 这是下面的代码。

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

这是我创建的 UserSchema

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

当在我的架构 .pre('save', ..) 中获取 this.password 时,它可以工作,但在我使用架构方法时显示未定义。 :(

这里是方法的实现

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

【问题讨论】:

    标签: javascript mongodb express mongoose mongoose-schema


    【解决方案1】:

    guide 中写道:

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-05
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      相关资源
      最近更新 更多