Mongoose pre findOneAndUpdate hook issues

后端 未结 4 727
春和景丽
春和景丽 2021-01-01 19:36

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

4条回答
  •  既然无缘
    2021-01-01 19:42

    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.

提交回复
热议问题