Remove record by id?
Asked Answered
B

6

25

Why I can't remove record by _id?

Code:

db.collection('posts', function(err, collection) {
   collection.remove({_id: '4d512b45cc9374271b00000f'});
});
Borrero answered 15/10, 2012 at 18:17 Comment(0)
G
67

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')});
});
Geanine answered 15/10, 2012 at 18:39 Comment(4)
Is it possible to remove array of ids at once?Droplight
@Droplight Sure, just use $in: {_id: {$in: idsArray}}Geanine
Couldn't find this answer in the documentation, very helpfulBluebill
latest mongodb for nodejs, it's ObjectId, not ObjectIDEntertaining
H
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");
    });
});
Herefordshire answered 14/3, 2016 at 7:31 Comment(0)
R
4

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')});
});
Rewrite answered 19/12, 2020 at 6:21 Comment(0)
R
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...

Rora answered 9/12, 2020 at 16:45 Comment(0)
A
0

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

Ard answered 7/9, 2021 at 10:43 Comment(0)
B
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);
});
Basket answered 3/2, 2022 at 15:41 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Cambrian

© 2022 - 2024 — McMap. All rights reserved.