chovy chovy - 4 years ago 138
Node.js Question

How do I remove a document with node-mongodb-native driver?

The operation returns saying

deleted: 0


const res = await ctx.db.collection(this.col).removeOne({ _id: ctx.params.id });


Not sure what I'm doing wrong here. GET requests by the
{ _id: <id> }
seem to work fine.

ctx.params.id
is defined and is the same as the ObjectId in the database.

According to this doc you can do
collection.removeOne()
(see example 2) https://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#remove

// Remove all the document
collection.removeOne({a:1}, {w:1}, function(err, r) {
test.equal(null, err);
test.equal(1, r.result.n);
db.close();
});

Answer Source

Try casting ctx.params.id to ObjectId, which is how mongodb stores identifiers internally.

import { ObjectId } from 'mongodb'

id = ObjectId(ctx.params.id)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download