how to insert autoincrement number with my mongoose collection

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

    Following the MongoDB tutorial, Create an Auto-Incrementing Sequence Field, you need to first create a separate counters collection to track the last number sequence used. The _id field contains the sequence name i.e. the userID field in the user collection and the seq field contains the last value of the sequence.

    To start with, insert into the counters collection the initial value for the userID:

    db.counter.insert(
       {
          "_id": "userID",
          "seq": 0
       }
    )
    

    Having populated the counters collection, generate its schema in Mongoose:

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

    Then redefine your user schema so that when you save a user model it first calls the counter model's findByIdAndUpdate() method to atomically increment the seq value and return this new value which can then be used as the next userID value:

    var userSchema = mongoose.Schema({
        "userID": { "type": String, "required": true },
        "firstname": { "type": String },
        "lastname": { "type": String },
        // other properties ...
        }, { "collection": "user" }
    );
    
    userSchema.pre("save", function (next) {
        var doc = this;
        counter.findByIdAndUpdate(
            { "_id": "userID" }, 
            { "$inc": { "seq": 1 } }
        , function(error, counter)   {
            if(error) return next(error);
            doc.userID = counter.seq.toString();
            next();
        });
    });
    

提交回复
热议问题