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);

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