Create unique autoincrement field with mongoose

Glen Swift picture Glen Swift · Apr 21, 2014 · Viewed 35.2k times · Source

Given a Schema:

var EventSchema = new Schema({
    id: {
        // ...
    },
    name: {
        type: String
    },
});

I want to make id unique and autoincrement. I try to realize mongodb implementation but have problems of understanding how to do it right in mongoose.

My question is: what is the right way to implement autoincrement field in mongoose without using any plugins and so on?

Answer

Natali picture Natali · Jan 18, 2020
const ModelIncrementSchema = new Schema({
    model: { type: String, required: true, index: { unique: true } },
    idx: { type: Number, default: 0 }
});

ModelIncrementSchema.statics.getNextId = async function(modelName, callback) {
    let incr = await this.findOne({ model: modelName });

    if (!incr) incr = await new this({ model: modelName }).save();
    incr.idx++;
    incr.save();
    return incr.idx;
};


const PageSchema = new Schema({
    id: { type: Number ,  default: 0},
    title: { type: String },
    description: { type: String }
});


PageSchema.pre('save', async function(next) {
    if (this.isNew) {
        const id = await ModelIncrement.getNextId('Page');
        this.id = id; // Incremented
        next();
    } else {
        next();
    }
});