I'm wondering if there is any reliable/reusable way to access the updated document during a mongoose post update middleware hook. All I seem to have access to is:
schema.post('update', function (result) {
console.log(this) // Mongoose Query, no relevant doc info
console.log(result) // Mongoose CommandResult, no relevant doc info
})
Thank you very much!
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins. Types of Middleware.
As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.
Mongoose supports middleware for the following operations: Aggregate. Document. Model.
In the Query object you receive in the post hook, you have access to the parameters sent to the query. You can get it like this
_conditions: { id: 'cjauvboxb0000xamdkuyb1fta' }
const id = this._conditions.id
this also works on update/updateOne/updateMany
schema.post('update', function (documents) {
this.model.find(this._conditions).then(documents => {
console.log(documents.length)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With