Skip to content

Instantly share code, notes, and snippets.

@scizers
Last active August 29, 2015 14:14
Show Gist options
  • Save scizers/97e68e64153421c0985b to your computer and use it in GitHub Desktop.
Save scizers/97e68e64153421c0985b to your computer and use it in GitHub Desktop.
auto increment with two queries
var mongoose = require('mongoose');
var counter = mongoose.Schema({
type: { type: String, index: { unique: true }},
seq: Number
});
// create the model for users and expose it to our app
module.exports = mongoose.model('counter', counter);
var getNextInvoiceNumber = function getNextInvoiceNumber(name , cb) {
var temp = new counter();
temp.seq = 1;
temp.type = name
temp.save(function (err , result) {
if(!err){
cb(1);
} else {
counter
.findOneAndUpdate( {type: name},
{$inc: {seq: 1}})
.exec(function (err, db_res) {
cb(db_res.seq)
});
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment