Mongoose - 如果存在,则增加 Subdoc 上的字段,否则创建新的

Ant*_*ito 3 javascript mongoose mongodb node.js

我正在尝试做的事情。

我有一个userSchema包含operationCountSchema对象列表的对象。我想要做的是创建一个静态方法,count如果存在(由 a 标识month_id)字段,则更新这些操作计数子文档之一上的字段。如果operationCountSchema当月不存在文档,则应创建一个新文档。有没有办法在猫鼬中实现这种行为?我试过使用 upsert 无济于事。怎么做呢?谢谢。

代码

var operationCountSchema = mongoose.Schema({
    month_id: String,
    count: { type: Number, default: 0 }
}, {_id : false});

var userSchema = mongoose.Schema({
    username : { type: String, unique: true, required: true },
    email: { type: String, unique: true, required: true },
    password: String,
    operation_counts: [operationCountSchema]
});

userSchema.statics.incrementOperationCount = function(userID, callback) {
    var currDate = new Date();
    var dateIdentifier = currDate.getFullYear() + "-" + currDate.getMonth();
    //NEED TO INCREMENT OPERATION COUNT IF ONE FOR MONTH EXISTS, 
    //ELSE IF IT DOES NOT EXIST, CREATE A NEW ONE.
}
Run Code Online (Sandbox Code Playgroud)

此外,欢迎任何有关实现此功能的替代方法的建议。

rob*_*lep 5

我想你想findOneAndUpdate()upsert : true

operationCountSchema.findOneAndUpdate({
  month_id : dateIdentifier,
}, { 
  $inc : { count : 1 }
}, {
  upsert : true
}, callback);
Run Code Online (Sandbox Code Playgroud)

(未经测试)