簡體   English   中英

通過 _id 在 ObjectId 類型上失敗查找 MongoDB 文檔

[英]Finding MongoDB documents by _id failing on the type of ObjectId

我正在努力通過 ReactJS 項目中的_id字段查找 MongoDB 文檔。

我的收藏中有看起來像這樣的文檔(例如):

    _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)結果如下:

Console.log 截圖

我應該如何滿足這個警告?

編輯:我像這樣定義我的應用程序/集合:

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

似乎是一個已知的BUG ,嘗試使用bson例如:

const bson = require('bson');

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

嘗試僅使用 _id 而不是“_id”

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

像這樣!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM