In express and mongodb I want delete document by id findOneAndDelete() Can not delete by _id, can only delete by field ! why ?
db.collection('quotes').findOneAndDelete({name: req.body.name}, (err, result) => { if (err) return res.send(500, err) }) var ObjectId = require('mongodb').ObjectId; var collection = db.collection('quotes'); collection.remove({_id: new ObjectId(req.body.id)}, function(err, result) { if (err) { console.log(err); } else { res.send('A darth vadar quote got deleted') } }); var mongodb = require('mongodb'); db.collection('quotes', function(err, collection) { collection.deleteOne({_id: new mongodb.ObjectID(req.body.id)}); });
Difference of three functions?
deleteOne() is used to delete a single document. remove() is a deprecated function and has been replaced by deleteOne() (to delete a single document) and deleteMany() (to delete multiple documents)
Both of them are almost similar except findOneAndRemove uses findAndModify with remove flag and time complexity will be a bit higher compare to findOneAndDelete because you are doing an update. Delete are always faster. Both functions send the exact same command over the wire to MongoDB.
Returns the deleted document.
Mongoose | findOneAndDelete() Function The 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.
In short:
findOneAndDelete()
returns the deleted document after having deleted it (in case you need its contents after the delete operation);deleteOne()
is used to delete a single documentremove()
is a deprecated function and has been replaced by deleteOne()
(to delete a single document) and deleteMany()
(to delete multiple documents)findOneAndDelete()
should be able to delete on _id
.
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