【问题标题】:Mongoose post save hook , update the documentMongoose post save hook , 更新文档
【发布时间】:2021-04-10 18:58:31
【问题描述】:

我正在使用 mongoose 后保存挂钩进行 API 调用。我想将该 API 的响应保存回上传到 MongoDB 的同一个文档。

UserSchema.post("save", async function (doc, next) {
  try {
    //This is the API call that gets fired and returns some data
    let data = await new sendDocToAPI(doc).send();
    //the data contains a exampleID which i want to save in exampleIDField.
    //I have predefined this exampleIDField field in the schema.
  } catch (error) {
    console.log("get -> error", error);
    next(error);
  }
});

我尝试了多种方法,例如使用 this.constructor.updateOne 或使用同一个文档来更新 doc.updateOne。它们似乎都不起作用。任何帮助表示赞赏

【问题讨论】:

  • 您应该可以使用doc.exampleIDField = data.exampleID; doc.save();,但这可能会导致无限循环,因为您正在再次保存文档,并且可能会再次触发保存后挂钩。因此,您可能需要检查 exampleIDField 是否存在,如果存在,请不要保存它甚至调用 api
  • 是的,这听起来不错。但是我可以更新文档吗?我没有更新帖子挂钩。或者即使在更新文档时也能帮助我理解我的保存帖子挂钩被调用??

标签: node.js mongodb mongoose hook


【解决方案1】:

玩了一个小时后,我发现这个解决方案有效。 它不会在您保存后修改您收到的文档,但会触发对传递给 .model() 函数的模型的新调用,并使用您想要的数据按条件 (id) 更新文档。

UserSchema.post("save", async function (doc, next) {
  try {
    let data = await doc
      .model("User")
      .finOneAndUpdate({ _id: doc._id }, { exampleIDField: "some ID you want to pass" });
  } catch (error) {
    console.log("get -> error", error);
    next(error);
  }
});

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 2021-01-08
    • 2014-03-22
    • 2014-08-28
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2019-01-31
    相关资源
    最近更新 更多