使用NodeJS更新MongoDB中的数组元素

db2dz4w8  于 2023-02-07  发布在  Go
关注(0)|答案(1)|浏览(140)

我想更新“ballpool”或“valorant”的游戏数组中的“paymentStatus”字段。我正在使用NodeJS。请帮助我如何通过将值“ballpool”或“valorant”作为参数来更新支付状态

{
"uniqueCode": "n5Eue",
"games": [
    {
        "ballpool": {
            "email": "aniketshaw@gmail.com",
            "name": "Aniket Shaw",
            "phone": "31231231",
            "ballpoolUID": "4232",
            "paymentStatus": false,
            "_id": "63de237567fa64e9711bb2b7",
            "__v": 0
        }
    },
    {
        "valorant": {
            "_id": "63de237567fa64e9711bb2b7",
            "email": "aniketshaw@gmail.com",
            "name": "Aniket Shaw",
            "phone": "31231231",
            "valorantUID": "4232",
            "paymentStatus": true,
            "__v": 0
        }
    }
],

}

vq8itlhq

vq8itlhq1#

这里有一个例子

let param = 'ballpool';
let setOperator;
let filterOperator;

if (param === 'ballpool') {
  setOperator = {
    'games.$[element].ballpool.paymentStatus': true,
  };

  filterOperator = {
    "element.ballpool": { $ne: null }
  };
} else if (param === 'valorant') {
  setOperator = {
    'games.$[element].valorant.paymentStatus': true,
  };

  filterOperator = {
    "element.valorant": { $ne: null }
  };
}

await Model.updateOne({
  uniqueCode: 'foo',
}, {
  $set: setOperator,
}, {
  arrayFilters: [filterOperator]
});

单击此处了解有关$[ identifier]的详细信息

相关问题