Auto Increment Sequence Mongoose

10,067

Probably this is why it happens: https://github.com/Automattic/mongoose/issues/3617#issuecomment-160296684

Use the setDefaultsOnInsert option. Or just manually use {$inc: {n:1}, $setOnInsert: {n:776} }

Share:
10,067
Skywalker
Author by

Skywalker

Updated on June 04, 2022

Comments

  • Skywalker
    Skywalker almost 2 years

    I implemented a auto increment sequence field in mongoose. I set the default/starting value as 5000. But it does not start from 5000, it starts from 1.

    Heres my code:

    My Counter Schema

    // app/models/caseStudyCounter.js
    // load the things we need
    var mongoose = require('mongoose');
    var bcrypt   = require('bcrypt-nodejs');
    
    // define the schema for our user model
    var caseStudyCounterSchema = mongoose.Schema({
       _id: {type: String, required: true},
       seq: {type: Number, default: 5000}
    
    });
    
    // methods ======================
    
    // create the model for users and expose it to our app
    module.exports = mongoose.model('caseStudyCounter', caseStudyCounterSchema);
    

    My Main Schema:

    // grab the mongoose module
    var caseStudyCounter = require('../models/caseStudyCounter');
    var mongoose = require("mongoose");
    
    // grab the bcrypt module to hash the user passwords
    var bcrypt   = require('bcrypt-nodejs');
    
    // define the schema for our model
    var caseStudySchema = mongoose.Schema({
         caseStudyNo: Number,
         firstName: String,
         lastName: String,
    
     });
    
    caseStudySchema.pre('save', function(next) {
      var doc = this;
    
    caseStudyCounter.findByIdAndUpdate({_id: 'caId'},{$inc: { seq: 1}},{"upsert": true,"new": true  }, function(error, counter)   {
        if(error)
            return next(error);
        doc.caseStudyNo = counter.seq;
        next();
    });
    
    });
     // module.exports allows us to pass this to other files when it is called
     // create the model for users and expose it to our app
     module.exports = mongoose.model('CaseStudy', caseStudySchema);
    

    I can't figure out why its starting form 1 when I have set the default as 5000. The sequence should be 5001, 5002, 5003 and so on. Any help will be greatly appreciated.