how to insert autoincrement number with my mongoose collection

前端 未结 3 784
一生所求
一生所求 2021-01-06 04:38

I am newbie to mongoose, I have a mongoose schema like this:

var user = mongoose.Schema({
    userID: {
        type: String,
        required:true
    },
           


        
3条回答
  •  忘掉有多难
    2021-01-06 05:16

    If you want an autoincrement prop based on the length of your collection, you can do something like this:

    UserSchema.pre("save", function (next) {
      if (this.isNew) {
        this.constructor.find({}).then((users) => {
          this.autoIncrementProp = users.length + 1;
          next();
        });
      }
    });
    

    isNew is a reserved Schema name (Boolean flag specifying if the document is new.)

提交回复
热议问题