【问题标题】:Type Error while getting instance of a model获取模型实例时输入错误
【发布时间】:2016-12-26 14:35:44
【问题描述】:

我添加了一个钩子来获取用户模型的实例来加密用户密码。但是我无法获取模型的实例。

这是我的代码

regUsers.pre('save',(next)=>{
      // get access to this user model
      const user = this;

      // generate salt the run call back
      bcrypt.genSalt(10,(err,salt)=>{

         if(err){ return next(err);}

        // hash(encrypt) our password using salt
         bcrypt.hash(user.password,salt,null,(err,hash)=>{

              if(err){ return next(err);}

              //overwrite plain text password with encrypted password
              user.password = hash;

              next();
         });
      })
});

我收到一个类型错误 TypeError:无法读取未定义的属性“密码”。 为什么我得到这个错误的任何原因?以及如何克服?

【问题讨论】:

标签: javascript node.js mongoose


【解决方案1】:

因为你用的是arrow function,试试经典的函数表达式。

可能 Mongoose 正在使用 call()apply()(或类似的东西)调用该回调,为其提供所需的上下文(在这种情况下,是对正在更新的文档的引用)。

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 2011-10-28
    • 2017-09-18
    • 2017-06-10
    • 2021-10-17
    • 1970-01-01
    • 2012-07-06
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多