Collection.insertOne ObjectId reference issue

Hi All, hope everyone is doing well.

I needed some guidance. In Realm I’m using collection.insertOne to insert a JSON record into the collection.



	"business_id": {"$oid":"606a770a62e058344e9c52a9"},
	"category_id": {"$oid":"5e182156bfa94d17ccefb4d9"},
	"sub_category_id": {"$oid":"5e182f96bfa94d17ccefb4e5"},
	"staff_id": {"$oid":"60b462c062e058344e9c5329"}

Issue is that when I insert from Realm it shows like the second dataset below. But if I take the same JSON and insert via Compass or browser then it shows correctly i.e. the ObjectId’s are imported correctly.

I understand JSON can’t store object information but I can’t figure out the best way to insert a record via Realm which has reference to ObjectId’s of different collection objects. I tried for ex

"business_id": ObjectId("606a770a62e058344e9c52a9") 


"business_id": {"_id":"606a770a62e058344e9c52a9"},

etc etc but no go. Either the online Realm validator doesn’t accept or same issue as screenshot above.

Any help would be appreciated. Thanks!

Hi @Sam and welcome in the MongoDB Community :muscle: !

I think what you are looking for is BSON.ObjectId("...").


Here is an example in action:

exports = async function(){
  const coll ="mongodb-atlas").db("test").collection("coll");
  await coll.deleteMany({});
  const result_insert_father = await coll.insertOne({"name": "father"});
  const father_id = result_insert_father.insertedId;
  console.log("ID of the father doc: " + father_id);
  await coll.insertOne({"name": "son", "parent": father_id});
  const son = await coll.findOne({"name": "son"});
  await coll.insertOne({"name": "forged", "parent": BSON.ObjectId("60b6b6779fa4e9249123a35e")});
  const forged = await coll.findOne({"name": "forged"});
  return "Done!";


> ran on Wed Jun 02 2021 00:57:09 GMT+0200 (Central European Summer Time)
> took 594.379835ms
> logs: 
ID of the father doc: 60b6bb46646de5c50f28b2c4
> result: 
> result (JavaScript): 

In Compass:

I hope this helps :-).

1 Like

Awesome! Thanks so much. This was the magic line which worked for me (for ex):
dataTemplate2.staff_id = BSON.ObjectId(json.ustandby_staff_id);

Thanks again!!

1 Like

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