A good reference of creating sequence and using it can be found at
https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
This can be achieved in Mongoose,
1) Step 1
From mongo shell create the counter collection as below
db.counters.insert({_id: "userid",seq: 0})
2)
create a counter schema as below (counter.js )
var mongoose = require('mongoose');
var counterSchema = {
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
};
module.exports = mongoose.model('Counter', counterSchema);
3) Use it (for example -- UserHandler.js)
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cchPerfApp');
var User = require('../model/user');
var counter = require('../model/counter');
var saveRequest = function() {
counter.findByIdAndUpdate({_id: 'userid'}, {$inc: { seq: 1} }, function(error, counter) {
if(error) {
console.log(error)
}else {
var user = new User();
user._id = counter.seq;
user.name = "xyz"
user.save(function(err){
}
}
}
}