22

Why I can't remove record by _id?

Code:

db.collection('posts', function(err, collection) {
   collection.remove({_id: '4d512b45cc9374271b00000f'});
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Sable
  • 357
  • 2
  • 4
  • 6

6 Answers6

65

You need to pass the _id value as an ObjectID, not a string:

var mongodb = require('mongodb');

db.collection('posts', function(err, collection) {
   collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
6

MongoDb has now marked the remove method as deprecated. It has been replaced by two separate methods: deleteOne and deleteMany.

Here is their relevant getting started guide: https://docs.mongodb.org/getting-started/node/remove/

and here is a quick sample:

var mongodb = require('mongodb');

db.collection('posts', function(err, collection) {
   collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')}, function(err, results) {
       if (err){
         console.log("failed");
         throw err;
       }
       console.log("success");
    });
});
Bill Tarbell
  • 4,933
  • 2
  • 32
  • 52
3

With TypeScript, you can to it using imports, instead of requiring the whole library

import { ObjectID } from 'mongodb'   

 

db.collection('posts', function(err, collection) {
   collection.deleteOne({_id: new ObjectID('4d512b45cc9374271b00000f')});
});
Len Joseph
  • 1,406
  • 10
  • 21
0

First include mongodb

var mongodb = require("mongodb");

You have to include the ObjectID from mongodb

var ObjectID = require('mongodb').ObjectID;

Then Use

var delete_id = request.params.id;//your id

 collection.deleteOne({_id: new mongodb.ObjectID(delete_id.toString())});

1000% works...

0

i think we have to require mongodb as const and use it with mongodb

AJB
  • 17
  • 7
0

I recently stumbled with this problem today and I find that the fix is:

const mongodb = require('mongodb');
const ObjectID = require('mongodb').ObjectID;
databaseName.collectionName.deleteOne({_id: new mongodb.ObjectID(id)} , (err)=>{
   if (err) throw err;
   console.log('Deleted'+id);
});
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Feb 03 '22 at 17:23