Home > Software design >  Delete MongoDB-document by its string-ID
Delete MongoDB-document by its string-ID

Time:12-16

I have a MongoDB-document that looks like this:

{
    _id: 'EXISTING_ID'
}

I want to delete this document and I tried to use this code to do so (leveraging the native node-js driver for MongoDB):

import { MongoClient, ObjectId } from "mongodb";

export const deleteDocumentWithId = (id: string) => {
  return MongoClient.connect(dbUrl, (err, db) => {
    if (err) {
      throw err;
    }

    const dbo = db.db("my-db");

    dbo.collection("my-collection").deleteOne({ _id: id }, (err, obj) => {
      if (err) {
        throw err;
      }
      db.close();
    });
  });
};

deleteDocumentWithId("EXISTING_ID");

however, the TypeScript-compiler throws an error, saying that no overloads match this call; _id should rather be of type ObjectId. However, if I replace the call with:

dbo.collection("my-collection").deleteOne({ _id: new ObjectId(id) }...

I get a runtime error, saying:

BSONTypeError: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

because the string "EXISTING_ID" is only 11 bytes in size.

However, I don't even think, that ObjectId is the right type to use here, as I don't see ObjectId in the database. The _id for the document above is a string.

In Java, there are the methods findById or deleteById, but I don't see these in NodeJS. Is there a way to achieve what I want, that I just haven't found yet?

CodePudding user response:

You need to specify type of _id field used in "my-collection". The Filter type of the deleteOne parameter uses InferIdType which is ObjectId by default.

At least inline:

dbo.collection<{_id: string}>("my-collection").deleteOne({ _id: id }, (err, obj) => {

but honestly, if you are using typescript you'd better have the proper named type for objects in "my-collection".

  • Related