Mongoose Find and Remove Mongoose Find and Remove mongodb mongodb

Mongoose Find and Remove


As you have noted, using the following will not return the document:

Data.find(query).remove().exec(function(err, data) {  // data will equal the number of docs removed, not the document itself}

As such, you can't save the document in ActionCtrl using this approach.

You can achieve the same result using your original approach, or use some form of iteration. A control flow library like async might come in handy to handle the async calls. It won't reduce your code, but will reduce the queries. See example:

Data.find(query, function(err, data) {  async.each(data, function(dataItem, callback) {    dataItem.remove(function(err, result) {      ActionCtrl.saveRemove(result, callback);    });  });});

This answer assumes that the ActionCtrl.saveRemove() implementation can take an individual doc as a parameter, and can execute the callback from the async.each loop. async.each requires a callback to be run without arguments at the end of each iteration, so you would ideally run this at the end of .saveRemove()

Note that the remove method on an individual document will actually return the document that has been removed.