Mongoose实例方法`this`不是指模型

Moo*_*her 3 mongoose mongodb node.js

编辑:我发现console.log(this)setPassword方法内部运行只返回哈希和盐.我不确定为什么会发生这种情况,但是它表明它this并没有像它应该那样引用模型.


我有以下模式与以下实例方法:

let userSchema = new mongoose.Schema({
  username: {type: String, required: true},
  email: {type: String, required: true, index: {unique: true}},
  joinDate: {type: Date, default: Date.now},
  clips: [clipSchema],
  hash: {type: String},
  salt: {type: String}
})

userSchema.methods.setPassword = (password) => {
  this.salt = crypto.randomBytes(32).toString('hex')
  this.hash = crypto.pbkdf2Sync(password, this.salt, 100000, 512, 'sha512').toString('hex')
}
Run Code Online (Sandbox Code Playgroud)

在这里调用实例方法,然后保存用户:

let user = new User()

user.username = req.body.username
user.email = req.body.email
user.setPassword(req.body.password)

user.save((err) => {
  if (err) {
    sendJsonResponse(res, 404, err)
  } else {
    let token = user.generateJwt()
    sendJsonResponse(res, 200, { 'token': token })
  }
})
Run Code Online (Sandbox Code Playgroud)

但是,当我users在mongo CLI中查看集合时,没有提及hashsalt.

{
 "_id" : ObjectId("576338b363bb7df7024c044b"),
 "email" : "boss@potato.com",
 "username" : "Bob",
 "clips" : [ ],
 "joinDate" : ISODate("2016-06-16T23:39:31.825Z"),
 "__v" : 0 
}
Run Code Online (Sandbox Code Playgroud)

Moo*_*her 12

它不工作的原因是因为我使用箭头方法.我必须使它成为一个正常的功能:

userSchema.methods.setPassword = function (password) {

原因是因为箭头函数this与常规函数的处理方式不同.有关详细信息,请参阅以下内容:

http://exploringjs.com/es6/ch_arrow-functions.html

  • 这实际上在文档中指出:https://mongoosejs.com/docs/guide.html#methods (2认同)