猫鼬实例方法"this"未引用模型
编辑:我发现在setPassword
方法中运行的console.log(this)
仅返回哈希值和盐值.我不确定为什么会发生这种情况,但是它表明this
并未正确引用该模型.
I have discovered that console.log(this)
ran inside the setPassword
method returns only the hash and salt. I'm not sure why this is happening, however it indicates that this
is not refering to the model as it should.
我具有以下具有以下实例方法的架构:
I have the following schema with the following instance method:
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')
}
在这里调用实例方法,然后保存用户:
The instance method is called here, then the user is saved:
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
集合时,没有提到hash
或salt
.
However, when I view the users
collection in the mongo CLI, there is no mention of hash
or salt
.
{
"_id" : ObjectId("576338b363bb7df7024c044b"),
"email" : "boss@potato.com",
"username" : "Bob",
"clips" : [ ],
"joinDate" : ISODate("2016-06-16T23:39:31.825Z"),
"__v" : 0
}
它不起作用的原因是因为我使用的是箭头方法.我必须将其设置为正常功能:
The reason it was not working was because I was using an arrow method. I had to make it a normal function:
userSchema.methods.setPassword = function (password) {
原因是因为箭头函数对this
的处理与常规函数不同.请查看以下内容以获取更多详细信息:
The reason is because arrow functions treat this
differently from regular functions. Please see the following for more detail: