I'm struggling to find MongoDB documents by their _id
field in my ReactJS project.
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:
const id = '5f6651112efc19f33b34fc39';
await mongoCollection.find({_id:ObjectId(id)});
ObjectId
is defined like so:
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:
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:
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>');
Seems like a known BUG, try to use bson
like:
const bson = require('bson');
const id = '5f6651112efc19f33b34fc39';
const bsonObjectId = new bson.ObjectId(id);
await mongoCollection.find({_id: bsonObjectId });