如何在我的猫鼬收藏夹中插入自动递增编号

Kar*_*hik 4 mongoose mongodb node.js

我是猫鼬的新手,我有这样的猫鼬架构:

var user = mongoose.Schema({
    userID: {
        type: String,
        required:true
    },
    seq: {
        type: Number,
        default: 0
    },
    firstname: {
        type: String
    },
    lastname: {
        type: String
    },
    dob: {
        type: String
    },
    email: {
        type: String,
        required: true
    },
    username: {
        type: String,
        required: true
    },
    displayname: {
        type: String
    },
    password: {
        type: String,
        required: true
    },
    mobile: {
        type: String
    },
    profilePic: {
        type: String
    },
    city: {
        type: String
    },
    gender: {
        type: String
    },
    profileType: {
        type: String,
        required: true
    },
    profileId: {
        type: String
    },
    isActive: {
        type: Number
    },
    ageVerified: {
        type: String
    },
    ipAddress: {
        type: String
    },
    key: {
        type: String
    },
    osType: {
        type: String
    },
    osVersion: {
        type: String
    },
    deviceName: {
        type: String
    },
    joinedDate: {
        type: String
    },
    connectedAccounts: [{
        profileType: {
            type: String
        },
        profileId: {
            type: String
        },
        email: {
            type: String
        }
    }]
}, {collection: 'user'});
Run Code Online (Sandbox Code Playgroud)

请注意,userID是一个自动递增数字字段,用于使用猫鼬查询插入值am,例如:

new user(contents).save(function (err,doc){};
Run Code Online (Sandbox Code Playgroud)

“内容”是一个对象,其中包含除userID以外的所有字段的数据,这是我的问题是在为其他字段插入记录时如何为userID(自动递增编号)插入值?我引用此链接来设置自动增量值...但是我不知道如何在猫鼬中使用它?

chr*_*dam 6

在MongoDB教程“ 创建自动递增序列字段”之后,您需要首先创建一个单独的counters集合以跟踪最后使用的数字序列。该_id字段包含序列名称,即userID用户集合中的字段,并且该seq字段包含序列的最后一个值。

首先,将计数器的初始值插入计数器集合userID

db.counter.insert(
   {
      "_id": "userID",
      "seq": 0
   }
)
Run Code Online (Sandbox Code Playgroud)

填充计数器集合后,在Mongoose中生成其架构:

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

var counter = mongoose.model('counter', counterSchema);
Run Code Online (Sandbox Code Playgroud)

然后重新定义用户模式,以便在保存用户模型时先调用计数器模型的findByIdAndUpdate()方法以原子方式递增seq值,然后返回此新值,该新值可以用作下一个userID值:

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();
    });
});
Run Code Online (Sandbox Code Playgroud)