Node.js,猫鼬,表达-无法从猫鼬模式方法获得结果

时间:2020-06-07 14:38:26

标签: node.js mongodb express mongoose

我有一个如下所示的用户架构:

const userSchema = new mongoose.Schema({
    ...
    resetToken: {
      type: String    
    }
})

下面是我在模式定义下定义的猫鼬模式方法:

userSchema.methods.generateResetToken = function() { 
  const reset_token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  bcrypt.hash(reset_token, 10, function(err, hash) {
    if (err) return winston.error(err.message)
    return hash
  })
}

以下是我的注册路线中的代码段:

user = new User(_.pick(req.body, ['username', 'email', 'password']))

bcrypt.hash(req.body.password, 10, function(err, hash) {
    if (err) return winston.error(err.message)

    // Getting undefined logged here 
    console.log(user.generateResetToken())

    user.password = hash
    user.save()
})

调用console.log(user.generateResetToken())时,我希望打印generateResetToken函数返回的值。相反,我得到了undefined的打印。当我将hash登录到控制台时,我可以确认正在生成hash,并且一切正常。

有人知道我为什么在调用undefined函数时在注册路线中得到generateResetToken吗?谢谢。

1 个答案:

答案 0 :(得分:1)

您目前没有从generateResetToken方法返回任何内容。您可以将回调函数传递给以下函数

userSchema.methods.generateResetToken = function(callback) { 
  const reset_token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  bcrypt.hash(reset_token, 10, callback)
}

现在您可以调用以下方法

user.generateResetToken(function(err, hash) {
    if (err) winston.error(err.message)
    console.log(hash)
  }))

还可以使用async/await

userSchema.methods.generateResetToken = async function() { 
  const reset_token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  return bcrypt.hash(reset_token, 10)
}
  try {
    const hash  = await myRec.generateResetToken();
  } catch (err) {
    winston.error(err.message)
  }