Coder Perfect

How can I delete documents using Mongoose in Node.js?

Problem

FBFriendModel.find({
    id: 333
}, function (err, docs) {
    docs.remove(); //Remove all the documents that match!
});

The above method does not appear to be effective. The records have not been destroyed.

Can someone fix?

Asked by TIMEX

Solution #1

If you don’t feel like iterating, try something else.

FBFriendModel.find({ id:333 }).remove( callback );

or

FBFriendModel.find({ id:333 }).remove().exec();

The Query returned by mongoose.model.find has a delete function.

Remove() has been deprecated in Mongoose v5.5.3. Instead, call deleteOne(), deleteMany(), or findOneAndDelete().

Answered by Yusuf X

Solution #2

UPDATE: Mongoose version is now available (5.5.3)

Remove() is no longer supported; instead, use deleteOne(), deleteMany(), or bulkWrite().

You can remove a document immediately with the.remove() method as of “mongoose”: “>=2.7.1,” which appears to me to be more efficient and easy to maintain than finding the document and then removing it.

See example:

Model.remove({ _id: req.body.id }, function(err) {
    if (!err) {
            message.type = 'notification!';
    }
    else {
            message.type = 'error';
    }
});

UPDATE:

As of mongoose 3.8.1, there are numerous methods for removing a document directly, such as:

For further details, see the mongoose API documentation.

Answered by Diosney

Solution #3

docs is a collection of documents. As a result, it lacks a mongooseModel. remove() is a method that is used to delete something from a

You can iterate through the array and remove each document one by one.

Alternatively, as you appear to be searching for documents based on a (likely) unique id, use findOne instead of find.

Answered by mtkopone

Solution #4

As of version 3.8.1, this is the best for me:

MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});

It also just necessitates one database call. If you don’t do anything else before the search and removal, you can use this.

Answered by José Pinto

Solution #5

remove() is no longer supported. Use deleteOne(), deleteMany(), or bulkWrite to remove items from your list ().

I use the following code.

TeleBot.deleteMany({chatID: chatID}, function (err, _) {
                if (err) {
                    return console.log(err);
                }
            });

Answered by Samyak Jain

Post is based on https://stackoverflow.com/questions/5809788/how-do-i-remove-documents-using-node-js-mongoose