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.

Example:

JSON

{
	"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") 

and

"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("...").

Doc: https://docs.mongodb.com/realm/functions/json-and-bson/#bson.objectid

Here is an example in action:

exports = async function(){
  const coll = context.services.get("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"});
  console.log(EJSON.stringify(son));
  
  await coll.insertOne({"name": "forged", "parent": BSON.ObjectId("60b6b6779fa4e9249123a35e")});
  const forged = await coll.findOne({"name": "forged"});
  console.log(EJSON.stringify(forged));
  return "Done!";
};

Output:

> 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
{"_id":{"$oid":"60b6bb46646de5c50f28b2ca"},"name":"son","parent":{"$oid":"60b6bb46646de5c50f28b2c4"}}
{"_id":{"$oid":"60b6bb47646de5c50f28b2d1"},"name":"forged","parent":{"$oid":"60b6b6779fa4e9249123a35e"}}
> result: 
"Done!"
> result (JavaScript): 
EJSON.parse('"Done!"')

In Compass:

I hope this helps :-).
Cheers,
Maxime.

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.