按字符串 ID 删除 MongoDB-文档

Delete MongoDB-document by its string-ID

我有一个 MongoDB-文档,看起来像这样:

{
    _id: 'EXISTING_ID'
}

我想删除此文档,我尝试使用此代码来执行此操作(利用 MongoDB 的本机 node-js 驱动程序):

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");

然而,TypeScript 编译器抛出错误,表示没有重载匹配此调用; _id 应该是 ObjectId 类型。但是,如果我将调用替换为:

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

我收到一个运行时错误,说:

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

因为字符串“EXISTING_ID”只有 11 个字节。

但是,我什至不认为 ObjectId 是在这里使用的正确类型,因为我在数据库中没有看到 ObjectId。上面文档的 _id 是一个字符串。

在Java中有方法findByIddeleteById,但我在NodeJS中没有看到这些方法。有没有办法实现我想要的,只是我还没有找到?

您需要指定“my-collection”中使用的 _id 字段的类型。 Filter type of the deleteOne parameter uses InferIdType 默认为 ObjectId。

至少内联:

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

但老实说,如果您使用的是打字稿,您最好在“my-collection”中为 objects 指定正确的命名类型。