Search code examples
node.jsmongoosemongoose-schemamongoose-auto-increment

how can I create a auto-increment field in mongoose


can any one tell me how can I create a auto-increment field in mongoose without using any library or plugin. Any simple and easy way..


Solution

  • there is a very simple and easy way to implement auto increment in mongoose by using mongoose pre save function. Here are my codes for user collection, try the same trick in your mongoose model(schema) to implement auto increment. Paste this code in your collection schema file and replace some variables(userSchema, user) according to your collection schema.

    userSchema.pre('save', function(next) {
        var currentDate = new Date();
        this.updated_at = currentDate;
    
        if (!this.created_at)
            this.created_at = currentDate;
    
        var sno = 1;
        var user = this;
        User.find({}, function(err, users) {
        if (err) throw err;
            sno = users.length + 1;
            user.sno = sno;
            next();
        });
    });