How to get document _id in mongoose pre updateOne hook?

Yuri Gor picture Yuri Gor · Oct 15, 2018 · Viewed 7.2k times · Source

I do updateOne for my model and have pre updateOne hook on my scheme like this:

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!' } }),
);

But I cant find any way to get currently updating document's id Here is a working test script: https://gist.github.com/YuriGor/04192230fb63542c1af5ff5c19b3a724

Note: in real life this will happen inside mongoose plugin, so I cant just save doc _id to some variable in parent scope, as I do in this script.

Answer

Yuri Gor picture Yuri Gor · Oct 18, 2018

Many thanks to vkarpov15 He found a typo in my code: double parentheses in the updateOne call, that's why there was no criteria in the query

so correct code should look like:

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!' } }
);