0

I used node mongoose. I need to update this array push new item into Breackfast(mealList.foodList.breackfast || any), I want to add new foodlist by time can you please give me suggestion for how to do,

    {
        "_id": "5fe43eb44cd6820963c98c32",
        "name": "Monday Diet",
        "userID": "5f225d7458b48d0fe897662e",
        "day": "Monday",
        "type": "private",
        "mealList": [
            {
                "_id": "5fe43eb44cd6820963c98c33",
                "time": "Breakfast",
                "foodList": [
                    {
                        "_id": "5fe43eb44cd6820963c98c34",
                        "foodName": "Eggs",
                        "Qty": "2",
                        "calories": "calories",
                        "category": "category"
                    }
                    
                ]
            },
            {
                "_id": "5fe43eb44cd6820963c98c36",
                "time": "Lunch",
                "foodList": [
                    {
                        "_id": "5fe43eb44cd6820963c98c37",
                        "foodName": "food1",
                        "Qty": "100g"
                    },
                ]
            }
        ],
        "createdAt": "2020-12-24T07:09:40.141Z",
        "updatedAt": "2020-12-24T07:09:40.141Z",
        "__v": 0
    }

I tried:

Diet.updateOne(
    { "Diet.mealList._id": req.body.mealId },
    // { $push: { "Diet.0.mealList.$.foodList": req.body.foodList } },
    { $push: { foodList: req.body.foodList } }
)
turivishal
  • 34,368
  • 7
  • 36
  • 59
  • I would suggest to alter your data model towards flat structure rather than nesting more than one level deep. Please refer : https://stackoverflow.com/questions/29634150/updating-nested-array-inside-array-mongodb – bron10 Dec 24 '20 at 07:31

1 Answers1

1

Few Fixes:

  • convert your string _id to object type using mongoose.Types.ObjectId
  • remove Diet from first and push object in foodList
Diet.updateOne({
  "mealList._id": mongoose.Types.ObjectId(req.body.mealId)
},
{
  $push: {
    "mealList.$.foodList": req.body.foodList
  }
})

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59