【问题标题】:How to get document _id in mongoose pre updateOne hook?如何在猫鼬 pre updateOne 钩子中获取文档_id?
【发布时间】:2018-10-19 02:53:32
【问题描述】:

我为我的模型做 updateOne 并在我的方案上预先设置了 updateOne 钩子,如下所示:

const schema = new mongoose.Schema({ name: { type: String } });
schema.pre('updateOne', async function() {
  fs.writeFileSync('./query.json', stringify(this, null, 2), 'utf-8');
});
const Model = mongoose.model('Model', schema);
let res = await Model.create({
  name: "I'll be updated soon",
});
console.log(res.name, res._id);
await Model.updateOne(
  ({ _id: res._id }, { $set: { name: 'I was updated!' } }),
);

但我找不到任何方法来获取当前更新的文档 ID 这是一个工作测试脚本: https://gist.github.com/YuriGor/04192230fb63542c1af5ff5c19b3a724

注意:在现实生活中,这将发生在 mongoose 插件中,所以我不能像在这个脚本中那样将 doc _id 保存到父范围内的某个变量中。

【问题讨论】:

    标签: node.js mongodb mongoose pre


    【解决方案1】:

    非常感谢vkarpov15 他在我的代码中发现了一个错字:updateOne 调用中有双括号,这就是为什么查询中没有条件

    所以正确的代码应该是这样的:

    const schema = new mongoose.Schema({ name: { type: String } });
    schema.pre('updateOne', async function() {
      console.log('query criteria',this.getQuery());// { _id: 5bc8d61f28c8fc16a7ce9338 }
      console.log(this._update);// { '$set': { name: 'I was updated!' } }
      console.log(this._conditions);
    });
    const Model = mongoose.model('Model', schema);
    let res = await Model.create({
      name: "I'll be updated soon",
    });
    console.log(res.name, res._id);
    await Model.updateOne(
      { _id: res._id }, { $set: { name: 'I was updated!' } }
    );
    

    【讨论】:

      猜你喜欢
      • 2021-05-17
      • 2022-11-12
      • 1970-01-01
      • 2017-11-24
      • 2016-11-12
      • 2023-03-09
      • 1970-01-01
      • 2018-06-01
      • 2019-10-06
      相关资源
      最近更新 更多