Home > Net >  Update an array element in MongoDB with NodeJS
Update an array element in MongoDB with NodeJS

Time:02-05

**I want to update the "paymentStatus" field in the games array of "ballpool" or "valorant".I am using NodeJS.So please help me how can i update the payment status by giving the value "ballpool" or "valorant" as parameter **

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

}

CodePudding user response:

Here's an example

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]
});

Learn more about $[identifier] here

  • Related