cplus
cplus

Reputation: 1115

mongoose finds but doesn't remove

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?

Upvotes: 0

Views: 32

Answers (1)

Aurélien Gasser
Aurélien Gasser

Reputation: 3120

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)
});

Upvotes: 1

Related Questions