FBFriendModel.find({ id: 333 }, function (err, docs) { docs.remove(); //Remove all the documents that match! });
The above doesn't seem to work. The records are still there.
Can someone fix?
remove() is deprecated and you can use deleteOne(), deleteMany(), or bulkWrite() instead. As of "mongoose": ">=2.7. 1" you can remove the document directly with the . remove() method rather than finding the document and then removing it which seems to me more efficient and easy to maintain.
To delete a record, or document as it is called in MongoDB, we use the deleteOne() method. The first parameter of the deleteOne() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted.
Mongoose | findOneAndDelete() FunctionThe findOneAndDelete() function is used to find a matching document, remove it, and passes the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.
If you don't feel like iterating, try
FBFriendModel.find({ id:333 }).remove( callback );
or
FBFriendModel.find({ id:333 }).remove().exec();
mongoose.model.find
returns a Query, which has a remove
function.
Update for Mongoose v5.5.3 - remove()
is now deprecated. Use deleteOne()
, deleteMany()
or findOneAndDelete() instead.
UPDATE: Mongoose version (5.5.3)
remove() is deprecated and you can use deleteOne(), deleteMany(), or bulkWrite() instead.
As of "mongoose": ">=2.7.1"
you can remove the document directly with the .remove()
method rather than finding the document and then removing it which seems to me more efficient and easy to maintain.
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 several methods that lets you remove directly a document, say:
remove
findByIdAndRemove
findOneAndRemove
Refer to mongoose API docs for further information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With