Last active
August 29, 2015 14:14
-
-
Save scizers/97e68e64153421c0985b to your computer and use it in GitHub Desktop.
auto increment with two queries
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 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); |
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 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