简体   繁体   中英

Mongoose Schema Cumulative Value in Field

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM