如何在 mongoose pre updateOne 挂钩中获取文档 _id?

How to get document _id in mongoose pre updateOne hook?

我为我的模型做了 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 保存到父范围中的某个变量。

非常感谢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!' } }
);