Mongodb Difference Remove() vs findOneAndDelete() vs deleteOne()

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?

1 Answer

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 document
  • remove() 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.

4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest