Home > database >  Mongoose Schema Cumulative Value in Field
Mongoose Schema Cumulative Value in Field

Time:09-10

I have a mongoose schema which is the following

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const personSchema = new Schema({
    name: {type: String},
    age: {type: Number},
    internalId: {type: Number},
})

personSchema.pre('save', function (next) {
    if (this.isNew) {this.id = this._id;}
    next()
})

const Person = mongoose.model("Person", personSchema);
exports.Person = Person

I would like the internal Id field to be a cumulative internal Id. This means that the first person will have internalId 1, the second internalId 2 and so on.

How can I proceed in doing so. Do I need to add a global value or make a function?

CodePudding user response:

You can use an npm package known as mongoose-sequence.

It allows you to define, what field you want to have auto-incremented, and it will be generated every time a new object of that model is created. Your code will look something like this if you used that package:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AutoIncrement = require('mongoose-sequence')(mongoose);

const personSchema = new Schema({
    name: {type: String},
    age: {type: Number},
});
personSchema.plugin(AutoIncrement, {inc_field: 'internalId'});
const Person = mongoose.model("Person", personSchema);
exports.Person = Person;
  • Related