【问题标题】:Mongoose pre hooks for save and update do not get called when i used a Model.findOneAndUpdate当我使用 Model.findOneAndUpdate 时,不会调用用于保存和更新的 Mongoose 预挂钩
【发布时间】:2020-05-18 21:31:46
【问题描述】:

我用猫鼬创建了一个快速应用程序。我还创建了一个保存和更新挂钩,如下所示:

userSchema.pre("update", async function save(next) {
    console.log("inside update")
     });

userSchema.pre("update", async function save(next) {
    console.log("inside save")
     });

但是每当我调用 Model.findOneAndUpdate() 时,不会调用 pre hook,saveupdate prehook 是否不适用于 findOneAndUpdate

【问题讨论】:

  • 嗨,你检查我的回答了吗?
  • @SuleymanSah 是的,先生,非常完美

标签: node.js mongoose


【解决方案1】:

正如 mongoose docs 中所述,pre 和 post save() 钩子不会在 update() 和 findOneAndUpdate() 上执行。

您需要为此使用findOneAndUpdate 钩子。但是您无法访问将使用此关键字更新的文档。如果您需要访问将要更新的文档,则需要对该文档执行显式查询。

userSchema.pre("findOneAndUpdate", async function() {
  console.log("I am working");
  const docToUpdate = await this.model.findOne(this.getQuery());
  console.log(docToUpdate); // The document that `findOneAndUpdate()` will modify
});

或者如果您可以像这样使用this.set() 设置字段值:

userSchema.pre("findOneAndUpdate", async function() {
  console.log("I am working");
  this.set({ updatedAt: new Date() });
});

假设我们有这个用户架构:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: String,
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

userSchema.pre("findOneAndUpdate", async function() {
  console.log("I am working");
  this.set({ updatedAt: new Date() });
});

module.exports = mongoose.model("User", userSchema);

还有这个用户文档:

{
    "updatedAt": "2020-01-30T19:48:46.207Z",
    "_id": "5e33332ba7c5ee3b98ec6efb",
    "name": "User 1",
    "__v": 0
}

当我们像这样更新这个用户的名字时:

router.put("/users/:id", async (req, res) => {
  let result = await User.findOneAndUpdate(
    { _id: req.params.id },
    { name: req.body.name },
    { new: true }
  );

  res.send(result);
});

updatedAt 字段值将设置为用户,并将更新。

【讨论】:

  • 第一个方法在我调用 docToUpdate.save() 之后起作用。但是 this.set({ }) 的第二种方式会更新文档,控制台记录正确的值,但不会将更改保存在数据库中。
猜你喜欢
  • 2020-05-13
  • 2018-01-04
  • 1970-01-01
  • 2019-04-10
  • 2015-08-29
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多