0

I am finding any document that matches my condition and I want to remove those docs.

MyModle.find({writer: req.body.id}, function(err, docs){
                if (err){ return console.log(err)}
                if (!docs || !Array.isArray(docs) || docs.length === 0){
                    return console.log('no docs found')}
                docs.forEach( function (doc) {
                    doc.remove();
                    console.log("Removed book with ID ",doc._id, "by writer ", req.body.id);
                });
            });

My console is printing the message as if the document was removed, but it is still in the collection. What is wrong here?

cplus
  • 1,115
  • 4
  • 22
  • 55

1 Answers1

1

As stated in the documentation for remove, the deletion is performed only if you either:

  • pass a callback function: doc.remove(function() { console.log('removed!'); });
  • or call exec: doc.remove().exec()

See also this question


To fix your code, you can replace:

doc.remove();
console.log("Removed book with ID ",doc._id, "by writer ", req.body.id)

with

doc.remove(function() {
    console.log("Removed book with ID ",doc._id, "by writer ", req.body.id)
});
Community
  • 1
  • 1
Aurélien Gasser
  • 3,043
  • 1
  • 20
  • 25