How to automatically generate custom id’s in Mongoose?

How to automatically generate custom id’s in Mongoose?


I’d like to manage my own _id‘s through Mongoose/MongoDB – as the default ones are pretty long and consume bandwidth.

The difficulty is that I need to create them (say, by incrementing a counter), but I need to do this in a concurrent environment (Node.JS). Is there a simple example I could follow that creates a schema, with a custom _id and a static method (or anything better) that automatically generates the next unique _id, whenever a new document is created?

Problem courtesy of: Ze Jibe


You could use Mongo’s findAndModify() to generate sequential values. Below is an example of this:

// (assuming db is a reference to a MongoDB database)
var counters = db.collection('counters');
var query = {'name': 'counterName'};
var order = [['_id','asc']];
var inc = {$inc:{'next':1}};
var options = {new: true, upsert: true};
counters.findAndModify(query, order, inc, options, function(err, doc) {

  if(err) {

  var id =;
  callback(null, id);

Although generating sequential IDs looks pretty on applications keep in mind that there are some drawbacks to them (e.g. when you need to split your database geographically) which is why Mongo uses the long pseudo-random keys that it does.

Solution courtesy of: Hector Correa


Leave a Reply

Your email address will not be published. Required fields are marked *