gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:24:14 24 4
gpt4 key购买 nike

我正在尝试做什么。

我有一个包含 operationCountSchema 对象列表的 userSchema。我想要做的是创建一个静态方法来更新这些操作计数子文档之一上的 count 字段(如果它存在(由 month_id 标识)字段)。如果当月不存在 operationCountSchema 文档,则应创建一个新文档。有没有办法在 Mongoose 中实现这种行为?我试过使用 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.
}

此外,欢迎就实现此功能的替代方法提出任何建议。

最佳答案

我想你想要findOneAndUpdate()使用 upsert : true:

operationCountSchema.findOneAndUpdate({
month_id : dateIdentifier,
}, {
$inc : { count : 1 }
}, {
upsert : true
}, callback);

(未经测试)

关于javascript - Mongoose - 如果存在,则在 Subdoc 上增加字段,否则创建新的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37518243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com