具有最大值的猫鼬 $inc
Mongoose $inc with maximum value
所以我目前正在尝试执行此操作
return this.model.findByIdAndUpdate(id, { $push: { certifiedBy: certifier } }, { $inc: {score: 1}}, { new: true })
这里的问题是 score
会无限制地增长,我想防止这种情况发生,所以当这种情况发生时,如果 score <= 5
但仍然添加 certifier
进入我的 certifiedBy
数组。
可以直接用 mongoose 完成吗,还是我必须先获取对象,检查它是否超过 5,然后在这种情况下调用不同的查询?
谢谢
你不能改变 $inc 的行为,但你可以在 5
之前做一个检查点来阻止它
return this.model.findOneAndUpdate({
_id: id,
score: {
$lte: 5
}
}, {
$push: { certifiedBy: certifier },
$inc: { score: 1 }
},
{
new: true
})
所以我目前正在尝试执行此操作
return this.model.findByIdAndUpdate(id, { $push: { certifiedBy: certifier } }, { $inc: {score: 1}}, { new: true })
这里的问题是 score
会无限制地增长,我想防止这种情况发生,所以当这种情况发生时,如果 score <= 5
但仍然添加 certifier
进入我的 certifiedBy
数组。
可以直接用 mongoose 完成吗,还是我必须先获取对象,检查它是否超过 5,然后在这种情况下调用不同的查询?
谢谢
你不能改变 $inc 的行为,但你可以在 5
之前做一个检查点来阻止它return this.model.findOneAndUpdate({
_id: id,
score: {
$lte: 5
}
}, {
$push: { certifiedBy: certifier },
$inc: { score: 1 }
},
{
new: true
})