猫鼬实例方法"this"未引用模型 [英] Mongoose instance method `this` does not refer to model

查看:55
本文介绍了猫鼬实例方法"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集合时,没有提到hashsalt.

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:

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

这篇关于猫鼬实例方法"this"未引用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆