我有一个包含两个字段的用户架构:
var userSchema = mongoose.Schema({
credits : { type: Number },
energy: { type: Number },
});
我想做的是根据另一个值递减其中一个值。
如果有任何积分,则将其递减1,否则将能量递减1。
一个简单的解决方案:
const user = await User.findById("123");
if (user.credits > 0) {
user.credits = model.credits - 1;
} else {
user.energy = user.energy - 1;
}
await user.save();
但是,我认为这对于并发并不安全。
所以我认为我需要做类似的事情:
await user.update({_id: userId}, { $inc: { energy: -1 } })
但是有什么方法可以检查在更新查询或其他好的解决方案中要减少的量吗?
答案 0 :(得分:0)
我想我找到了一个解决方案,但不确定是否是最佳解决方案。
const res = await UserModel.updateOne(
{ _id: id, coins: { $gt: 0 } }, // Matches if coins are positive
{ $inc: { coins: -1 } }, // If it's the case decrement coins
);
// If none was modified, coins must be 0,
// so we decrement energy instead
if (!res.nModified) {
await UserModel.updateOne(
{ _id: id, energy: { $gt: 0 } }, // Make sure energy never goes negative
{ $inc: { energy: -1 } },
);
}