Mongoose实例方法`this`不参考模型

编辑:我已经发现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') } 

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

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

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

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

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

userSchema.methods.setPassword = function (password) {

原因是因为箭头函数与常规函数不同。 请参阅以下详细信息:

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