Mongoose pre findOneAndUpdate hook issues Mongoose pre findOneAndUpdate hook issues mongoose mongoose

Mongoose pre findOneAndUpdate hook issues


You can do smthng like that ->

source.pre('findOneAndUpdate', function (next) {    console.log('------------->>>>>> findOneAndUpdate: ');    this._update.$set.objects = [];    this._update.$set.people = [];    this._update.$set.events =  [];    next();});

pay attention to _update.$set because in the context "this" will be a query. So you can easily add anything you want!


The documentation states:

Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated.

An update action generally updates a document that only exists in the database (it tells the MongoDB server: "find document X and set property X to value Z"), so the full document isn't available to Mongoose and, hence, you can't update the counts (which requires access to at least the arrays whose length you want to determine).

As an aside: why do you need separate *Count properties in your schema anyway? If you want to query for arrays matching a certain size, you can use the $size operator on the arrays directly.

If you really do need the count properties, then for each update, you need to track the number of changes you made to each of the arrays (in terms of the number of items added/deleted) and use the $inc operator to adjust the counts.


I had a similar issue when I used the updateOne method and was also going to use the updateOne pre hook to make intermittent update before saving to the database. couldn't find a way for it to work. I ended up using the findOneAndUpdate pre hook and doing the updateOne in it.

schema.pre('findOneAndUpdate', async function(next){      const schema = this;     const { newUpdate } = schema.getUpdate();     const queryConditions = schema._condition     if(newUpdate){       //some mutation magic       await schema.updateOne(queryConditions, {newUpdate:"modified data"});        next()     }     next()})