Why I can't remove record by _id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
Why I can't remove record by _id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
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')});
});
$in
: {_id: {$in: idsArray}}
–
Geanine ObjectId
, not ObjectID
–
Entertaining 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");
});
});
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')});
});
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...
i think we have to require mongodb as const and use it with mongodb
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);
});
© 2022 - 2024 — McMap. All rights reserved.