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

Yur*_*Gor 2 pre mongoose mongodb node.js

我为我的模型做 updateOne 并且在我的方案上有 pre 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!' } }),
);
Run Code Online (Sandbox Code Playgroud)

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

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

Yur*_*Gor 5

非常感谢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!' } }
);
Run Code Online (Sandbox Code Playgroud)