findOne by ObjectId not working

I can see from my Data Services web page a record of:

{ _id: ObjectId("5bbdf280831b976548aa14e8"),
  library: 'Library1',
  collection: 'Collection1',
  media: 'Images',
  object: 'Image3',
  info: 'Image: 1/1/Images/Image3 Info', …

and I want to use the findOne to get it:

  let id = arg.query.id
  const nid = new BSON.ObjectId(id)
  
  const ret = await collection.findOne({ _id:  id})
  console.log(id, nid, ret)

and I’m getting:

logs: 
5bbdf280831b976548aa14e8 5bbdf280831b976548aa14e8 null

It is supposed to return the above record, no?

Hello @MBee,

Yes, you can query by ObjectId. Here’s an example from mongosh

> var oid = new ObjectId()
> db.test.insertOne({_id: oid})
{
  acknowledged: true,
  insertedId: ObjectId("63b90d4db1b02cfcf851c729")
}
> db.test.findOne({_id: oid})
{ _id: ObjectId("63b90d4db1b02cfcf851c729") }

Check out this example. Hope it helps

Hi @MBee,

In this code snippet you are passing the string id in findOne() instead of the binary ObjectId nid you created. These are different data types, and will not match in a query. Both values appear similar in your console.log() output because console logging is implicitly calling toString() to return a printable version of each variable.

Try changing the last line above to:

const ret = await collection.findOne({ _id:  nid})

Regards,
Stennie

1 Like

Duh! I guess I was so intimidated by the brand new things that I overlooked something extremely obvious. Thanks.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.