node.js - Mongoose 中间件更新后不起作用

标签 node.js mongoose mongoose-middleware

回调未被调用,但应该按照 mongoose 中间件中的记录:

schema.post('update', function(error, res, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'));
  } else {
    next(error);
  }
});

我尝试了预更新,它有效:

schema.pre("update", function(next) {
    console.warn('results', "i am called");
    next(new Error("error line called"));
});

但我想要的是更新后:

schema.post("update", function(error, res, next) {
    console.warn('results', "is this called?");
});

实际模型更新:

MyModel.update({_id : 123}, req.payload, function (err, numberAffected, rawResponse) {
    reply("done!");
});

我没有看到日志 console.warn('results', "is this called?");,这是预期的吗?

附: 机器:Windows 10, Mongoose 版本:4.5.8

最佳答案

访问the docs ,看起来您应该在 schema.post 的回调函数中只包含一个代表已更新文档的参数。 Hook 可能永远不会调用您的回调,因为它从未提供其余参数。例如:

schema.post("update", function(doc) {
  console.log('Update finished.');
});

而不是:

schema.post("update", function(error, res, next) {
  console.log('Update finished.');
});

关于node.js - Mongoose 中间件更新后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41755806/

相关文章:

mongodb - 使用 Mongoose 中间件查找在任一字段中值匹配的文档

node.js - 使用客户端和服务器模仿node-webkit的功能

node.js - 试图模拟 github webhook 请求,得到 : "X-Hub-Signature does not match blob signature"

ajax - 如何在 NodeJS/ExpressJS 中正确重定向?

node.js - Mongoose 使用 presave 中间件推送到数组

mongodb - 访问 Mongoose 父文档以获取子文档中的默认值

node.js - docker-compose 和 traefik 微服务之间的通信

node.js - 无法使用 nestjs/mongoose 连接 mongoDB

performance - 用于线程消息的 MongoDB/Mongoose 模式(高效)

javascript - MongoDB 对填充字段的查询