【问题标题】:Node.js, mongoose, express - cannot get result from a mongoose schema methodNode.js、mongoose、express - 无法从 mongoose 模式方法获取结果
【发布时间】:2020-06-07 23:47:35
【问题描述】:

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

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,并且一切正常。

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案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)
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 2011-12-07
      • 2012-12-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多