Nikola B.
Nikola B.

Reputation: 606

Get affected records with mongoose update command

How can I get ids of affected records inside database when executing mongoose update command with multi:true option?

    MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, { multi: true }, function (err, raw) {
      if (err) return handleError(err);
      console.log('The raw response from Mongo was ', raw);
    });

This will return number of affected documents, but how can I know their ids without running another query inside database?

Upvotes: 2

Views: 862

Answers (1)

Akrion
Akrion

Reputation: 18525

The update operation with or without the multi: true option returns a WriteResult which does not have a property containing such details. Only various counts.

When it comes to mongoose as per their documentation you only get and err and rawResponse in their callback on success:

The callback function receives (err, rawResponse).

err is the error if any occurred rawResponse is the full response from Mongo

So you basically get the WriteResult from mongo nothing more nothing less.

So no you can not get a convenient list of the updated _id although you could probably do something with the post update middleware where you can run the filter part of the update and store the _ids somewhere I guess for audit etc.

Upvotes: 3

Related Questions