Home > Back-end >  How to update sub array item in MongoDB, JavaScript
How to update sub array item in MongoDB, JavaScript

Time:09-18

So let's say I have this piece of code:

const old = await Sports.findById(sportId);

And it returns the following:

{
    _id: "sdsdsds",
    name: "sdsdsds",
    enabled: true,
    markets: [
        {
            enabled: true,
            defId: "LOOKATME",
            name: "sdsdsd",
        },
        {
            enabled: false,
            defId: "dfsdfdsfs",
            name: "sdsdfsdsd",
        },
    ]
}

Now, let's say I want to update the market with the defId of "LOOKATME" so it enabled becomes false. Would it be possible to added inside an update function such as this:

const updated = await Sports.findByIdAndUpdate(old, [LOGIC], {new: true});

How would I go about doing this so the output is this:

{
    _id: "sdsdsds",
    name: "sdsdsds",
    enabled: true,
    markets: [
        {
            enabled: false, // this is what changed
            defId: "LOOKATME",
            name: "sdsdsd",
        },
        {
            enabled: false,
            defId: "dfsdfdsfs",
            name: "sdsdfsdsd",
        },
    ]
}

CodePudding user response:

const updated = await Sports.updateOne({_id: old._id, "markets.defId": "LOOKATME"}, {$set: {"markets.$.enabled": false}}, {new: true});
  • Related