2

I'm writing a function in MongoDB Realm that I want to use as a custom resolver for GraphQL. Part of the function should get a specific document by its id. According to the documentation I can get access to the Atlas DB by using context.services.get('mongodb-atlas'). Here's the simplified code extract:

exports = async () => {
  const cluster = context.services.get('mongodb-atlas');
  const collection = cluster.db('my-db').collection('my-coll');
  return await collection.findOne({"_id": "61d33d2059c38ef0584c94f8"});
}

However, the findOne() call returns null. I know that the id above is valid, because I can successfully call collection.find() and list all the documents with their ids.

What I've tried

  • findOne({"_id": "61d..."}) - returns null
  • findOne({"_id": new ObjectId("61d...")}) - error: "ObjectId" is not defined.
  • Explicitly declaring ObjectId with const ObjectId = require('mongodb').ObjectId as recommended here - error: "MongoDB Node.js Driver is not supported".
  • Declaring ObjectId with const ObjectId = require('bson').ObjectId - findOne() returns null again.

Can you recommend any other avenue by which to do this lookup?

Jans Rautenbach
  • 394
  • 4
  • 13
  • Can you add `.catch(err => console.error(`Failed to find document: ${err}`));` and see if the err reveals any further details? It's a good idea to include error trapping is they can be very handy when troubleshooting - maybe so in the this case as well. – Jay Jan 05 '22 at 19:01
  • Tried it. No error gets thrown. `null` is a valid return value if no object is found. Problem is that the passed-in string is a valid ObjectId – Jans Rautenbach Jan 08 '22 at 14:49

1 Answers1

0

First thing I would suggest is - let's identify where the script is failing. We know for certain, the below should work.

exports = async () => {
let tmp_collection = context.services.get("mongodb-atlas").db("my-db").collection("my-coll");
return await tmp_collection.findOne({});
}

After you can confirm that the above works, give this a try:

    return await context.services.get("mongodb-atlas").db("my-db").collection("my-coll").findOne({"_id":new BSON.ObjectId("61d33d2059c38ef0584c94f8")});

Here is your code, but fixed:

exports = async () => {
  const cluster = context.services.get('mongodb-atlas');
  const collection = cluster.db('my-db').collection('my-coll');
  return await collection.findOne({"_id": new BSON.ObjectId("61d33d2059c38ef0584c94f8")});
}
oblivion02
  • 557
  • 5
  • 14