1 min read

How to use MongoDB IDs in Meteor.JS?

Meteor.JS is a revolutionary client-server javascript framework which allow to manage the data in the same Mongo-style way in the browser or in the server.

The weird part is that the Meteor.JS collections don't use the MongoDB IDs (ObjectID) but another primary key generation style (Random string), so what to do if you want to reuse MongoDB collection with MongoDB ID style?

The Meteor IDs

Meteor.uuid()
=> ​"cfe6ef5c-da4a-4c27-ac19-c534d151c40f"

mhm.. no, it's a long ID.

Random.id()
=> "v2PrCTPea6tM6JNHn"

damn, this is a too short ID, let's try..

new Meteor.Collection.ObjectID()._str
=> "478fb4594a40064145bb7373"

Bingo, this is an original MongoDB style ID! However this kind of ID can be default in the Collections initialized like this:

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

Now if you want to use this ID system some changes are needed:

Queries

Events.findOne(this.params._id); // Before
Events.findOne(new Meteor.Collection.ObjectID(this.params._id)); // After

Templates

  Handlebars.registerHelper('_id', function () {
      return this._id._str;
  });

Handle with care, it overrides the original `_id` behavior.