Q: MongoDB Auto Increment Sequence I am trying to get auto increment sequence in mongodb. I have stored a function for the same in system collection. Below is the function I created for it, which increments counters collection for given _id by 1. So far I was calling it with db.eval which got depreciated now. I am looking for an alternative to this. I cam across to one solution is MapReducer, though I am not sure how does it work. Could someone please help me to achieve it without db.eval().  
Auto Increment function. 
db.system.js.save(
{
 _id: "getNextSequenceValue",
 value : function getNextSequenceValue(sequenceName){

       var sequenceDocument = db.counters.findAndModify({
          query:{_id: sequenceName },
          update: {$inc:{sequence_value:1}},
          new:true
       });

       return sequenceDocument.sequence_value;
    }
});

Below is the piece of code, how I was calling above function.
mongoose.connection.db.eval("getNextSequenceValue('Staff_ID')", function(err, nextStaffID) {
        if(err){
            return res.status(200).json({ success: false, message: 'Sequence Error. ' + err});
        }
})

Appreciated your help!! Thanks!!

A: If you use a Mongoose one way to implement it would be like this:
const sequenceSchema = new mongoose.Schema({
    name: String, value: { type: Number, min: 0 }
});

sequenceSchema.index({ name: 1 }, { unique: true });

sequenceSchema.statics.next = async function nextSequenceValue(name) {
    const { value } = await this.findOneAndUpdate(
        { name }, { $inc: { value: 1 } },
        { upsert: true, new: true });
    return value;
};

const Sequence = mongoose.model('Sequence', sequenceSchema);

With usage:
const nextSeqVal = await Sequence.next('My Sequence Name');

