I\'m trying to update counts on a pre hook. The issue is that for some unknown reason the findOneAndUpdate
hook doesn\'t have access to the document, as far as
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, sothis
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.