Created
June 30, 2013 15:25
-
-
Save hectorcorrea/5895570 to your computer and use it in GitHub Desktop.
A quick way to get incremental ids for documents in MongoDB via the findAndModify feature. This snippet gets a new incremental/sequential ID. Keep in mind that this is not a good strategy when you database is horizontally distributed which is why MongoDB out of the box uses a much more complex algorithm to calculate _id. Use at your own risk. [S…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getNewId = function(db, callback) { | |
var counters = db.collection('counters'); | |
var query = {'name': 'myCustomId'}; | |
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); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment