简体   繁体   中英

Mongoose auto increment for existing collection

I have an existing collection named users with the following schema. I want to add a new auto incremented field named userNumber in it. I have seen thecounter based solution but failed to implement those mainly because I don't see the working where it will do the numbering for the existing documents plus where to place that code. So my question is how to add userNumber field with auto incrementing values and how to populate values for this column in existing records

user.model

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
    userType: {
      type: String,
      required: false,
    },
    uid: {
      type: String,
      required: false,
    },
    firstName: {
      type: String,
      required: true,
    },
    lastName: {
      type: String,
    },
    email: {
      type: String,
      lowercase: true,
    },
});

module.exports = mongoose.model('User', userSchema);

First you can add userNumber to your User schema and when you want to create new user then add value to userNumber automatically by get old value from database and incremented.

here is how it works with counter:

export const CounterSchema = new mongoose.Schema({
  _id: {type: String, required: true},
  seq: {type: Number, default: 0}
},

the _id could be anything you want. In that case i would name it user

the seq (sequence) is your current count, starting at 0.

to update the counter you will have to call it every time you create a new user.

const callBack: MongooseDocument = await counterModel.findOneAndUpdate({_id: 
'user'}, {$inc: {seq: 1}}, {new: true});

to access the new count you call: newCount = callBack.toJSON().seq

to make it work for you current situation, you will have to loop through your users and update them one by one. When that is done, you update your counter and after that you do it whenever you create a user..

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