按 _id 查找 MongoDB 个文档,但 ObjectId 类型失败

Finding MongoDB documents by _id failing on the type of ObjectId

我很难通过我的 ReactJS 项目中的 _id 字段找到 MongoDB 文档。

我的 collection 有这样的文档(例如):

    _id: ObjectId("5f6651112efc19f33b34fc39")
    title: "This is a title"
    status: true

我在函数中使用这段(大大简化的)代码来查找与传入的 id 相匹配的文档:

const id = '5f6651112efc19f33b34fc39';
await mongoCollection.find({_id:ObjectId(id)});

ObjectId 定义如下:

const ObjectId = require('mongodb').ObjectID;

然而,即使我将 id 变量硬编码为数据库中文档中的 ObjectId 字符串,它也会失败并显示此错误:

Uncaught (in promise) Error: invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [{"type":"Buffer","data":[]}]

await 行之前打印出 idObjectId(id) 结果如下:

我应该如何满足这个警告?

编辑:我正在这样定义我的 app/collection:

const app = new Realm.App({ id: "<app-id>", timeout: 10000 });
const mongo = app.services.mongodb('mongodb-atlas');
const mongoCol = mongo.db('<databaseName>').collection('<collectionName>');

尝试只使用 _id 而不是“_id”

const id = "5f6651112efc19f33b34fc39"
await mongoCollection.find({_id:ObjectId(id)});

喜欢这个!

似乎是已知的 BUG,请尝试使用 bson,例如:

const bson = require('bson');

const id = '5f6651112efc19f33b34fc39';
const bsonObjectId = new bson.ObjectId(id);
await mongoCollection.find({_id: bsonObjectId });