module.exports = function(mongoose) {
// Creates a new Mongoose Schema object
var Schema = mongoose.Schema;
// Collection to hold counters/sequences for ids
var CountersSchema = new Schema({
_id: { type: String, required: true },
sequence: { type: Number, required: true }
},{
versionKey: false
}
);
// Creates the Model for the Attachments Schema
var Counters = mongoose.model('Counters', CountersSchema);
var getNext = function(collection, callback) {
var query = {_id: collection};
var update = {$inc: {sequence: 1}};
var options = {upsert: true};
Counters.findOneAndUpdate(query, update, options, function(err, counter) {
if (err) // handle error
callback(counter.sequence);
});
}
return {
getNext: getNext
}
}
getNext('person', function(id) {
// create a new person with the next id
});
Warning
Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with larger numbers of documents. Typically the default value ObjectId is more ideal for the _id.