【问题标题】:Delete MongoDB-document by its string-ID通过字符串 ID 删除 MongoDB 文档
【发布时间】:2022-01-18 00:13:50
【问题描述】:

我有一个如下所示的 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 中看不到这些。有没有办法实现我想要的,但我还没有找到?

【问题讨论】:

  • IdType 定义为字符串。见mongodb.github.io/node-mongodb-native/4.0/…
  • @Alex-Blex 感谢您的评论!您能否将其表述为我接受的答案?另外,您能否包括这将如何应用于我上面显示的代码?我真的无法理解您链接到的文档!

标签: node.js database mongodb uniqueidentifier


【解决方案1】:

您需要指定“my-collection”中使用的_id 字段的类型。 deleteOne参数的Filter类型使用InferIdType,默认为ObjectId。

至少内联:

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

但老实说,如果您使用的是 typescript,则最好为“my-collection”中的对象使用正确的命名类型。

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多