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)
此外,欢迎任何有关实现此功能的替代方法的建议。
我想你想findOneAndUpdate()用upsert : true:
operationCountSchema.findOneAndUpdate({
month_id : dateIdentifier,
}, {
$inc : { count : 1 }
}, {
upsert : true
}, callback);
Run Code Online (Sandbox Code Playgroud)
(未经测试)
| 归档时间: |
|
| 查看次数: |
2145 次 |
| 最近记录: |