Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to automatically generate custom id's in Mongoose?

How to automatically generate custom id's in Mongoose?

Problem

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

Solution

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) {
    callback(err);
    return;
  }      

  var id = doc.next;
  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

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to automatically generate custom id's in Mongoose?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×