【发布时间】: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