[英]findAndModify conditionally in mongoDB
如果promotional
值大於我想將其設置為30
的credit
值,我想更新它,否則我希望它設置為20
。
文檔
{
"_id" : "XX",
"promotional" : 200,
}
代碼
let creditDeduct= 100
let accountId = 'xx'
this.adapter.collection.findAndModify(
_id = accountId,
[["_id", "asc"]],
{ "$inc": { $cond: { if: { $gte: [ '$promotional', creditDeduct ] }, then: 30, else: 20 }} },
{ "new": true, "upsert": true },
function(error, doc) {
if (doc) {
console.log(doc);
}
if(error){
console.log(error);
}
}
);
錯誤
{ MongoError: Cannot increment with non-numeric argument: {$cond: { if: { $gte: [ "$promotional", 100 ] }, then: 30, else: 20 }}
at Connection.<anonymous> (/xx/xx/node_modules/mongodb/lib/core/connection/pool.js:466:61)
at Connection.emit (events.js:198:13)
at processMessage (/xx/xx/node_modules/mongodb/lib/core/connection/connection.js:364:10)
at Socket.<anonymous> (/xx/xx/node_modules/mongodb/lib/core/connection/connection.js:533:15)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17) ok: 0, errmsg: 'Cannot increment with non-numeric argument: {$cond: { if: { $gte: [ "$promotional", 100 ] }, then: 30, else: 20 }}', code: 14, codeName: 'TypeMismatch', name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} }
當你想設置值時,你需要使用set
var credit= 100
db.collection.updateMany({"promotional":{$gt:credit}},{$set:{"promotional":20}})
db.collection.updateMany({"promotional":{$lte:credit}},{$set:{"promotional":30}})
此外, $inc
將僅適用於數字數據類型。 你能檢查promotional
值是number
而不是string
嗎?
在 Mongo Compass 中,您可以單擊編輯按鈕來設置其數據類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.