我有下面的嵌套对象在某些conditions.based之后进行更新,最后我想更新promotional
或transactional
值。
{
"_id" : "XX1",
"credit" : {
"sms" : {
"credit" : {
"promotional" : 0,
"transactional" : 1231
}
},
"viber" : {
"credit" : {
"promotional" : 10,
"transactional" : 50
}
},
"whatsapp" : {
"credit" : {
"promotional" : 30,
"transactional" : 40
},
}
},
}
条件将基于传递的变量值。
accountId = "XX1",
channel = "sms",
messageType = "promotional",
credit = 150
这些是在更新前应该检查的条件。
_id
应该与accountId
匹配channel='sms'
,则应该选择credit.sms
messageType = "promotional"
然后检查促销值是否大于credit
credit
值(credit.sms.credt.promotional),则应使用:(credit.sms.credt.promotional)-credit
更新发布于 2020-04-17 19:04:55
您可以使用计算属性名称和$inc运算符来执行此操作。类似于:
YourModel.findOneAndUpdate(
{ _id: accountId, [`credit.${channel}.credit.${messageType}`]: { $gte: credit } },
{ $inc: { [`credit.${channel}.credit.${messageType}`]: -credit} }
)
https://stackoverflow.com/questions/61277632
复制