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 } }
)
1
  • I would suggest to alter your data model towards flat structure rather than nesting more than one level deep. Please refer : stackoverflow.com/questions/29634150/… Commented Dec 24, 2020 at 7:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.