String or ObjectID for _id

Hi,

I have a simple question. What do you mainly use for _id:

  • String
  • ObjectID
  • Both
  • Other
0 voters

You are missing ‘Both’.
For my stuff it really depends on how the collections are filled with docs.

You are right.

Modified

Follow up question: if you use ObjectID, why?

One reason could be because documents can be added by external applications that use Mongo’s default behavior.

  1. It’s smaller (12 bytes instead of 17).
  2. It’s generated automatically for all bulk operations (e.g., insertMany or bulkWrite).
  3. It contains a timestamp (second resolution is fine for “when was it created”). It’s at the beginning, so sorting by ObjectId sorts by creation time (documents created within the same second have some total and stable order).
2 Likes

But this one works for the ones created directly by Mongo or by using rawCollection, not for the ones created by Meteor as it is random.

TIL :laughing:

Sounds much better. Not keen to try migrate though :sweat_smile:

Is it right to consider that for someone who only uses methods server side and no publications (other than the default ones in the Accounts package) it is fine to use ObjectID?

I see this is suggested in the documentation:

Events = new Meteor.Collection('events', {idGeneration: 'MONGO'});

For me it would be better if I could avoid the extra createdAt field which I also need to index.
12 bytes over 17 bytes is not as bad as having an extra field and index.

It’d be nice to see Meteor use uuidv7 as a default going forward rather than the random hex. Since it also has a timestamp, then we could sort by _id which already has an index. And if you have a complex system, I’d imagine you’d rather use uuidv7 than Mongo’s proprietary ObjectId.

Related discussion here for anyone interested: Support for objects other than ObjectID/String as ids ¡ meteor/meteor ¡ Discussion #12337 ¡ GitHub

1 Like

Yep, that’s right.

You can use it normally, even with publications.

Yes and no.Sure, UUIDs are more common than ObjectIds, but v7 is not always the best choice. The fact that it stores the creation date means that the creation date is public – that’s not always fine. Also, MongoDB does not support it natively, as the UUID function generates only v4 format.

I do agree that a “native” support in Meteor (i.e., idGeneration: 'UUID') would be nice.

1 Like