9

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!

Jared Reich
  • 247
  • 4
  • 9
  • Instead of `schema.post('update', ...)` try `schema.post('findOneAndUpdate', function(result) { console.log(result); });` instead to get access to the modified doc. – chridam Jan 16 '17 at 16:08

3 Answers3

2

this also works on update/updateOne/updateMany

schema.post('update', function (documents) {
  this.model.find(this._conditions).then(documents => {
    console.log(documents.length)
  }
})
haofly
  • 829
  • 12
  • 15
1

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 only works if you pass in the id during your function as a parameter. Is there a way to get the id of the document if you are not querying by id? – Harrison Cramer Jun 22 '20 at 01:27
-2

Schema.post('update') is only used in error handling (custom error messages)

// The same E11000 error can occur when you call `update()`
// This function **must** take 3 parameters. If you use the
// `passRawResult` function, this function **must** take 4
// parameters
Schema.post('update', function(error, res, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'));
  } else {
    next(error);
  }
});

If you wanted to add an updatedAt timestamp to every update() call for example, you would use the following pre hook.

Schema.pre('update', function() {
  this.update({},{ $set: { updatedAt: new Date() } });
});

Read official docs

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • I'm not the downvoter, but it's probably because you misunderstood the docs. An error handler middleware must take 3 or 4 parameters, if not, it will be treated as a normal middleware. It has nothing to do with it been a post update middleware. – Leia Nov 02 '18 at 02:18