[英]Finding MongoDB documents by _id failing on the type of ObjectId
I'm struggling to find MongoDB documents by their _id
field in my ReactJS project.我正在努力通过 ReactJS 项目中的_id
字段查找 MongoDB 文档。
My collection has documents that looks like so (for example):我的收藏中有看起来像这样的文档(例如):
_id: ObjectId("5f6651112efc19f33b34fc39")
title: "This is a title"
status: true
I'm using this (greatly simplified) code in a function to find the documents that match the id
passed in:我在函数中使用这个(大大简化的)代码来查找与传入的id
匹配的文档:
const id = '5f6651112efc19f33b34fc39';
await mongoCollection.find({_id:ObjectId(id)});
ObjectId
is defined like so: ObjectId
定义如下:
const ObjectId = require('mongodb').ObjectID;
Yet even if I hard coded the id
variable to be the ObjectId string from the document in my database, it fails with this error:然而,即使我将id
变量硬编码为数据库中文档中的 ObjectId 字符串,它也会因以下错误而失败:
Uncaught (in promise) Error: invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [{"type":"Buffer","data":[]}]
Printing out id
and ObjectId(id)
before the await
line results in the following:在await
行之前打印出id
和ObjectId(id)
结果如下:
How should I be satisfying this warning?我应该如何满足这个警告?
Edit: I'm defining my app/collection like so:编辑:我像这样定义我的应用程序/集合:
const app = new Realm.App({ id: "<app-id>", timeout: 10000 });
const mongo = app.services.mongodb('mongodb-atlas');
const mongoCol = mongo.db('<databaseName>').collection('<collectionName>');
Try just _id instead of "_id"尝试仅使用 _id 而不是“_id”
const id = "5f6651112efc19f33b34fc39"
await mongoCollection.find({_id:ObjectId(id)});
Like this!像这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.