Home > Mobile >  how to push a data into an array of objects in mongodb based on the name into the the completed arra
how to push a data into an array of objects in mongodb based on the name into the the completed arra

Time:11-02

I want to add a current date into a user meal plan breakfast and find the name of an object like a banana on condition and add a date to the completed array?

this is the mongoose document .every food item contains an array of completed and every time a request is sent it will add or remove date on the completed array. i should be able to push date to the completed array

{
    "_id": {
        "$oid": "616f193e9eb4ca14afc47fa8"
        },
    "date": {
        "$date": "2021-10-19T15:52:09.298Z"
    },
    "email": "[email protected]",
    "firstName": "john",
    "lastName": "doe",
    "password": "$2b$10$jKylT8MKsUl7ZS03EVi7SecQ1eWuB37J5rLVTU/C8VXBwkWQQo6EK",
    "role": "user",
    "token": "eyJhbGciOiJIQb-JA2kcKxWquDaM",
    "mealplan": {
        "dietType": ["Halal", "Vegetarian", "Vegan"],
        "religionType": ["Agnostic", "Muslim", "Christian", "Buddhist"],
        "ethinicType": ["Asian", "Native American"],
        "_id": "6179a178ba48312626059d44",
        "name": "first meal",
        "budget": 2000,
        "orac": 163,
        "medicinal": 0,
        "breakfast": [
        {
            "type": "breakfast",
            "completed": [],
            "fdcId": 1103194,
            "name": "Carrots, raw, salad",
            "numbers": 1,
            "unit": "100 grams",
            "recurring": {
            "startTime": "08:30",
            "endTime": "09:30",
            "startDate": "2021-10-28",
            "endDate": "2021-11-03",
            "daysofweek": []
            }
        },
        {
            "type": "breakfast",
            "completed": [],
            "name": "orange juice",
            "numbers": 1,
            "unit": "100 mililiters",
            "recurring": {},
            "orac": 10,
            "medicinal_value": 0,
            "nutrition": []
        },
        {
            "type": "breakfast",
            "name": "banana",
            "completed": [],
            "numbers": 1,
            "unit": "100 grams"
        }
        ]
    },
    "__v": 0
}

when I send a post request it will be the name of the food and date. date show be added to the completed array in name of food

CodePudding user response:

use arrayFilter like this
for example we want add to food with name of bnana

db.collection.update({},
{
  $push: {
    "mealplan.breakfast.$[arr].completed": "date" // put date here
  }
},
{
  arrayFilters: [
    {
      "arr.name": "banana" // name of food here
    }
  ]
})

https://mongoplayground.net/p/lbzcF0YPuDF

  • Related