Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access updated document during mongoose post update middleware?

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!

like image 633
Jared Reich Avatar asked Jan 16 '17 15:01

Jared Reich


People also ask

What is document middleware in mongoose?

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.

How do you use findOneAndUpdate?

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.

What does Upsert do in mongoose?

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.

In which operations does Mongoose support middleware?

Mongoose supports middleware for the following operations: Aggregate. Document. Model.


2 Answers

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
like image 164
abhinav gupta Avatar answered Nov 04 '22 15:11

abhinav gupta


this also works on update/updateOne/updateMany

schema.post('update', function (documents) {
  this.model.find(this._conditions).then(documents => {
    console.log(documents.length)
  }
})
like image 28
haofly Avatar answered Nov 04 '22 15:11

haofly