Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Find and Remove

I'm trying to delete multiple documents that satisfy a query. However I need the data of those documents for storing them in a separate collection for undo functionality. The only way I got this to work is with multiple queries:

Data.find(query).exec(function(err, data)
{
    Data.remove(query).exec(function(err2)
    {
        ActionCtrl.saveRemove(data);
    });
});

Is there a better way? In this post: How do I remove documents using Node.js Mongoose? it was suggested to use find().remove().exec():

Data.find(query).remove().exec(function(err, data)
{
    ActionCtrl.saveRemove(data);
});

However data is usually 1, don't ask me why. Can I do this without infinitely nesting my queries? Thanks!

like image 312
Micha Schwab Avatar asked Jul 27 '15 20:07

Micha Schwab


1 Answers

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.

like image 190
snozza Avatar answered Nov 15 '22 05:11

snozza