Convert initial _id to a normal value

Hello,

What is the best way to convert the normal Realm object _id to a more normal value that I can display to the user?
For example:

5742a6af744f6b0dcf0003d1      convert to     321432
5406e4c49b324869198b43     convert to     353213

Hi. the bytes of the object id do have specific meanings as you can see here: https://www.mongodb.com/docs/manual/reference/method/ObjectId/

That being said, what you are asking for is really an anti-pattern. If you want something like an auto-incrementing user_id field that is customer-facing then you should consider either:
(a) making the _id field an integer (note: I wouldn’t recommend doing this)
(b) have a separate field called user_id that gets its value by incrementing a singleton documents counter variable. You can have this still be a unique index if you want: https://www.mongodb.com/docs/manual/core/index-unique/

Trying to synthesize meaning out of an ObjectId (other than to figure out the time it was created) will likely lead to more confusion than it is worth.

@Daniel_Gabor : I also agree with @Tyler_Kaye, doesn’t make much sense to convert object_id. May I also know why you are doing this?

Hello @Mohit_Sharma @Tyler_Kaye ,

At the moment the id looks like: 5742a6af744f6b0dcf0003d1

I want to change to a more normal value, for example only number value: 4321543.

It will be easier for the user to comunicate a problem to us with a simplier id of the object than with that big number/letter id.

There are no easy way? Like hashing that value or something?

If you look at the link I sent above, the objectId does store some meaning that you could use. Particularly you could use the time-stamp bytes, but they are no guaranteed to be unique. Similarily you could just hash the _id if you want, but again, that is not guaranteed to be unique, especially if you are hashing to a low number (6 digits).

All around, can you do what you want to do…kind of. However, I would really reccomend having a second field that is user_facing. The ObjectId / _id is normally an internal field and not visible to the user (the same as a UUID field would be), but if you need a more readable user_id, you should have a separate field for that and have application logic / unique indexes be in charge of managing it.

1 Like