how to insert autoincrement number with my mongoose collection

前端 未结 3 770
一生所求
一生所求 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:11

    Considering that the logic of schema.findByIdAndUpdate is "return the current value and THEN increment it", you can also use @chridam's solution with the following edit:

    var counter = mongoose.model('counter', counterSchema);
    
    
    userSchema.pre("save", function (next) {
      var doc = this;
      counter.findByIdAndUpdate(
          { "_id": "userID" }, 
          { "$inc": { "seq": 1 } }
      , function(error, c /*counter*/)   {
          if(error)
            return next(error);
          else if(!c) {
            c = new counter({ _id: "userID" }, { $inc: { seq: 1 } };
            c.save(function() {
              doc.userID = (c.seq - 1) + '';
              next();
            });
          } else {
            doc.userID = counter.seq.toString();
            next();
          }
      });
    });
    

    Please, note that this solutions makes your code function from scratch WITHOUT forcing you to initialize the DB.

    The tricks lies in the first round of the loop. counter is undefined, so you need to initialize it, but if you initialize it equal to 0, next tick the code tries to assign userID=0 again!

    This is because on one hand there is the logic of schema.findByIdAndUpdate that reads-first the value and then increments it, on the other hand you need a logic that assigns-first the value though.

    You can join these two logics by making the algorithm skip the first step and setting variable values as above.

    Notes: counterSchema is the same as chridam's:

    counterSchema = mongoose.Schema({
      "_id": { "type": String, "required": true },
      "seq": { "type": Number, "default": 0 }
    });
    

提交回复
热议问题