猫鼬问题 .findByIdAndUpdate 和预更新挂钩

A.S*_*S.J 3 mongoose node.js mongoose-schema

我有一个名为 UserSchema 的猫鼬模式,它存储有关所有用户的信息。我想让用户更改他的信息,我尝试使用 .findByIdAndUpdate。这是相关代码:

router.post("/updateprofile", function(req,res,next) {
    const {id, org, tel, email, firstName, lastName} = req.body;
    Users.findByIdAndUpdate(id, {org : org, tel : tel, email : email, firstName : firstName , lastName : lastName}, function (err, response) {
        if (err) throw err
        res.json(response);
    });

});
Run Code Online (Sandbox Code Playgroud)

然而,试图改变信息的时候,我收到以下错误消息:Cannot read property 'password' of undefined。我很确定这是由预更新挂钩引起的,但我无法删除它,因为我的“忘记密码”功能需要它。这是代码:

UserSchema.pre('findOneAndUpdate', function (next) {
    this.update({},{ $set: { password: 
    bcrypt.hashSync(this.getUpdate().$set.password, 10)}} )
    next();
});
Run Code Online (Sandbox Code Playgroud)

我对它为什么使用那个 prehook 感到困惑,因为它在钩子中寻找findOneandUpdate以及当我尝试更改我正在使用的数据时findByIdAndUpdate

我尝试使用,.update()但这也不起作用。有谁知道我做错了什么以及如何解决它?

Dan*_*ary 11

看起来 getUpdate 不是你想要的,试试这样:

    UserSchema.pre('findOneAndUpdate', function (next) {
    this._update.password = bcrypt.hashSync(this._update.password, 10)
    next();
});
Run Code Online (Sandbox Code Playgroud)

关于您的第二个问题,findByIdAndUpdate 是 findOneAndUpdate 的包装器。这是直接来自Mongoose 源代码的代码供您参考

Model.findByIdAndUpdate = function(id, update, options, callback) {
  if (callback) {
    callback = this.$wrapCallback(callback);
  }
  if (arguments.length === 1) {
    if (typeof id === 'function') {
      var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n'
          + '  ' + this.modelName + '.findByIdAndUpdate(id, callback)\n'
          + '  ' + this.modelName + '.findByIdAndUpdate(id)\n'
          + '  ' + this.modelName + '.findByIdAndUpdate()\n';
      throw new TypeError(msg);
    }
    return this.findOneAndUpdate({_id: id}, undefined);
  }
Run Code Online (Sandbox Code Playgroud)

代码中的注释如下:

/**
 * Issues a mongodb findAndModify update command by a document's _id field.
 * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
 *
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读源代码:https : //github.com/Automattic/mongoose/blob/9ec32419fb38b74b240280aaba162f9ee4416674/lib/model.js