Monday, February 24, 2014

Create an Auto-Incrementing (auto id) sequence field using mongodb + nodejs using findAndModify

Today I was wanted to use a running number  _id column rather than the ObjectId used by Mongodb. After looking at the mongo db documents and trying it in node.js, I could not get it to work. Problem was I was using node wrapper to connect to mongo db. So I have to refer wrapper documentation not the mongodb documentation to figure out the functions and parameters

function getNextId(name) {
var counters = db.collection('counters');
counters.findAndModify({_id:name}, [['_id','asc']], {$inc : {"seq":1}}, {upsert:true, new:true},             function(err, object) {
     if (err) console.warn(err.message);
     else
     console.log(object.seq);
});
}

how to use ?
getNextId("messageId"); will print the next id .

2 comments:

  1. Hi did you get any answer to this question ?

    ReplyDelete
  2. This function will create a collection called collection in mongodb. If you call this function like

    getNextId("messageId");

    It will return with messageid 1 and increase everytime you call this function. Make sure to use mongodb 1.4.8 .. Newer versions has a problem

    ReplyDelete