-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Access document in pre hook query middleware #8218
Comments
I am not sure if I understand correctly, but I believe accessing the document before updating it through a findOneAndUpdate hook is not possible, as this operation is an atomic one and is not being split into multiple "parts", therefor mongoose does not actually "know" what the document looks like while handling this query. Because of this, the "this" only refers to the query and not the document. However, you can of course first fetch the object through findOne or findById, and then call "save()" on it, which will give you the document in the pre('save') hook of the model. |
@BenSower is right, you would need to execute a separate query to get the document being updated in pre('findOneAndUpdate'), because findOneAndUpdate is a single atomic operation sent to mongodb. You can access the document in post('findOneAndUpdate') though |
This is the documentation:
However, if you define pre('updateOne') document middleware, this will be the document being updated. That's because pre('updateOne') document middleware hooks into Document#updateOne() rather than Query#updateOne().
|
@MichaelMikeJones I opened up #9434 to fix that 👍 |
Actually @MichaelMikeJones the docs describe the behavior correctly, they mention the difference between |
Do you want to request a feature or report a bug?
Documentation Issue
What is the current behavior?
In a pre hook for findOneAndUpdate I need to get the document being saved. I can see there is an issue that was closed previously for this that simply had a link to the documentation, however the documentation for this is not straight forward at all. It does describe how "this" functions in query middleware but I do not see anywhere in the documentation that says how to actually get the document in query middleware.
I generally find the Mongoose documentation to be very difficult to read which makes it significantly harder and less attractive to use Mongoose.
Can someone please indicate how to access the document in the a pre hook for query middleware?
#7497
The text was updated successfully, but these errors were encountered: