Inserting into mongodb with an ObjectId reference field

Hi
Trying to insert a document that refers to another doc, using the mongodb node insert action.
For example for collections:
orgs { name: string }
employees { name: string, org_id: objectId }

I want to insert an employee document { name: “bla”, org_id: ObjectId(“68676a2f5528af331c3b8bff”) }

Since ObjectId isn’t a valid JSON it can’t be used in the mongodb node I’ve tried replacing it with either a simple string and and $oid object:
{ name: “bla”, org_id: “68676a2f5528af331c3b8bff” }
{ name: “bla”, org_id: { $oid: “68676a2f5528af331c3b8bff” } }

Both fail the validation bsonType: “objectId”

If there’s no validation on the field, I can insert in either format, but then when doing $lookup there’s no match between the org._id and employee.org_id
The $oid format actually sets a value to an object { $oid: ‘…’ } instead of an ObjectId(…)

Has anybody succeeded this?

hi Oren, welcome to community. maybe you can try this

{
“name”: “bla”,
“org_id”: ObjectId(“68676a2f5528af331c3b8bff”)
}

Let’s see how close I am

Hi @Oren_Shefi ! Welcome to community!
Here is a workflow example of your needs (maybe), hopefully it will helps!

If it helps, please mark my msg as solution, thanks!

Thanks very much!
Awesome idea.

The problem remains - the value inserted into the DB is { $oid: … } rather than ObjectID(…)

Using mongodb 8.0.11 inside Atlas, if that’s any help

test> db.employees.insertOne({ name: 'mike', org_id: ObjectId('6867b18a121b9bb12a9baf3d') })
{
  acknowledged: true,
  insertedId: ObjectId('6867b235121b9bb12a9baf3e')
}
test> db.employees.find()
[
  {
    _id: ObjectId('6867b235121b9bb12a9baf3e'),
    name: 'mike',
    org_id: ObjectId('6867b18a121b9bb12a9baf3d')
  }
]

... after running flow ...

test> db.employees.find()
[
  {
    _id: ObjectId('6867b235121b9bb12a9baf3e'),
    name: 'mike',
    org_id: ObjectId('6867b18a121b9bb12a9baf3d')
  },
  {
    _id: ObjectId('6867b25b546cfd46e7336223'),
    name: 'blah',
    org_id: { '$oid': '6867b18a121b9bb12a9baf3d' }
  }
]

How do I this inside n8n?

Can you screenshot the result from Mongo Db?
Because mine it’s fine with the workflow.

could it be a db version?

How about inside the mongodb console? Can you share it?

That is the mongodb console
Thanks!

Sorry I mean from MongoDb Website.
Did you try my flow btw?

yes tried the flow - that’s how i got to the point i am. thanks!

the mongodb site shows both docs having ObjectID
but querying by org_id returns only the non $oid one
and i can’t query on $oid



I have no idea, trying unlimited time with no results. Same as you.