Mongodb + Node.js: delete multiple documents and return them

Unfortunately, deleteMany() passes only the error and deleteWriteOpResult to your callback so no actual documents are passed.

This is not just with Node.js - this is how actually db.collection.deleteMany works in Mongo:

Returns: A document containing:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

  • deletedCount containing the number of deleted documents

You have to do it with two requests, but you can abstract it away in a single function - e.g. if you're using the native Mongo driver you can write something like this:

function getAndDelete(collectionName, filter, callback) {
  var collection = db.collection(collectionName);
  collection.find(filter, function (err, data) {
    if (err) {
      callback(err);
    } else {
      collection.deleteMany(filter, function (err, r) {
        if (err) {
          callback(err);
        } else {
          callback(null, data);
        }
      });
    }
  });
}

that you can call with:

getAndDelete('testcollection', {
    id: {
        $in: ['1', '2', '3']
    }
}, function (error, response) {
    // ...
});

This code is not tested but just to give you an idea where to start from.

Note: there used to be findAndRemove() but it's been deprecated.