簡體   English   中英

mongoose 模式方法返回未定義

[英]mongoose schema method returning undefined

我想創建一個使用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' } }
);

在我的架構中獲取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);
  }
};

指南中它說:

不要使用 ES6 箭頭函數 ( => ) 聲明方法。 箭頭函數明確阻止綁定this ,因此您的方法將無法訪問文檔...

所以在這種情況下,您只需要將UserSchema.methods.validatePassword = async (data) => {...更改為UserSchema.methods.validatePassword = async function(data) {...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM