Refer autogenerated _id on another field on insert

Hello there.

I have a field on my collections that needs the information of _id. The problem is that _id is auto generated on server so I can’t populate this field before saving it first. Is there a way to achieve this without making 2 calls to the server? (1 for saving and then 1 for update)

Just to make a simple analogy, in an sql env, I would create a trigger afterInsert and then populate this field.

Thanks in advanced.

You can always generate a value yourself (e.g. a UUID string) and set it as the _id value in db.

I know that, but I think the best way to guarantee uniqueness is leaving this job to the server, right?

not really, use UUID is good enough,

Actually, it is the driver that generates the _id, not the server.

Nothing stops you from creating the _id with

const _id = new ObjectId() ;

and then use this _id for your other field.

Hi Steeve, thanks for your reply.

Ok, so now i have 2 questions:

  1. in a single instance, if I use new ObjectId() (without parameters), the driver will guarantee uniqueness?
  2. how about in a distributed systems environment? if N systems are doing the same, the chances of collision will increase considerably, right?


I have been reading and considering that process and machine ids are used in the composition of objectId, it shouldn’t cause collisions. Therefore, calling new ObjectId() should be enough for my problem.

Thanks for the replys

1 Like