Remove record by id?
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')});
});
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')});
});
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");
});
});