在另一个函数

时间:2018-06-07 16:35:06

标签: javascript bcrypt mongoose-schema

我试图验证用户,但我在邮递员中收到此错误

{
"error": "data and hash arguments required"
}

我的用户模型如下所示:

const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const SALT_WORK_FACTOR = 10
const Schema = mongoose.Schema

const UserSchema = new Schema({
  username: { type: String, required: true, index: { unique: true } },
  password: { type: String, required: true }
})
UserSchema.pre('save', function (next) {
  let user = this

  // only hash the password if it has been modified(or is new)
  if (!user.isModified('password')) return next()

  // generate a salt
  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) return next()

    // hash the password along with our new salt
    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) return next(err)
      // override the cleartext password with the hashed one
      user.password = hash
      next()
    })
  })
})
UserSchema.methods.comparePassword = (candidatePassword, callback) => {
  console.log('Password', this.password)// undefined
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    callback(err, isMatch)
  })
}
module.exports = mongoose.model('userData', UserSchema, 'userData')

我发现传递给bcrypt compare函数的this.password解析为undefined。如何访问上面UserSchema实例中定义的密码变量?

1 个答案:

答案 0 :(得分:1)

显然在javascript中,plot(sol.t,a[1,:])在对象调用函数之前没有赋值,从而将this绑定到方法的所有者(调用对象)。 在上面的问题中,我使用this箭头函数,其es6绑定到直接的周围范围(词法范围),因此无法找到在<<1}}上定义的属性this strong> UserSchema ,并且不受箭头函数中password范围的限制 例如:

this

注意es6箭头函数内的var Utils = { printName: function(somename) { console.log(somename) } } var person = { firstName: "Gregory", lastNames: ["Baltimore", "Barry", "Derrick", "Evanson"], fullName: function() { this.lastNames.forEach(lastname => { //this points to person object Utils.printName(this.firstName + " " + lastname) //output Gregory Baltimore Gregory Barry Gregory Derrick Gregory Evanson }) } } person.fullName() 指向作为静态范围(词汇)的person对象。让我们从es5的角度看一下相同的代码

this

你会注意到firstname被打印为undefined。这是因为在es5 var Utils = { printName: function(somename) { console.log(somename) } } var person = { firstName: "Gregory", lastNames: ["Baltimore", "Barry", "Derrick", "Evanson"], fullName: function() { this.lastNames.forEach(function(lastname) { //this points to global object Utils.printName(this.firstName + " " + lastname) //output undefined Baltimore undefined Barry undefined Derrick undefined Evanson }) } } person.fullName() 超出范围,因此默认情况下(Javascript怪癖)绑定到全局对象。在浏览器中,这个全局对象是Nodejs中的窗口,如果没有用户定义,则全局对象是Nodejs环境(运行时)。(例如,在模块导出中) 为了解决我的问题我默认使用es5函数,因为密码属性 绑定到我已定义为UserSchema的全局对象。因此密码属性已正确解析

this

更多相关内容可以在这里找到 Understand JavaScript’s “this” With Clarity, and Master It

也在这里 Arrow functions and the ‘this’ keyword