1

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();
});
chovy
  • 72,281
  • 52
  • 227
  • 295

1 Answers1

1

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

import { ObjectId } from 'mongodb'

id = ObjectId(ctx.params.id)
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • Why would I have to do that when I don't anywhere else I use ids? – chovy Feb 05 '17 at 10:51
  • @chovy I'm actually not sure, but you can try. Your code above looks alright to me. – zurfyx Feb 05 '17 at 10:53
  • That works! man, why on this method but not any other? weird. – chovy Feb 05 '17 at 10:54
  • @chovy I'd love to give you an answer to this, but I don't know really. I know that mongoose does this by itself, not sure why mongodb does not (and specially why it doesn't just in the deleteOne). – zurfyx Feb 05 '17 at 10:55
  • is it good practice to always do this? I don't seem to have any issues with `.find({ _id: ctx.params.id })` – chovy Feb 05 '17 at 10:57
  • @chovy considering this case, I would. You are avoiding false positives. Either way, a redundant ObjectId won't hurt. MongoDB requires ObjectId's anyway under the hood (and will always return you ObjectIDs on find) – zurfyx Feb 05 '17 at 10:59