Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

407
Vistas
Mongoose - How to push object in nested array of objects

I have this data structure in my MongoDb database:

    "menu": [
            {
                "dishCategory":"61e6089f209b802518e2b4a4",
                "dishMeals": [
                    {
                        "dishMealName": "Burger King",
                        "dishMealIngredients": "Burger lepinja, bbq sos, berlin sos, zelena"
                        "dishMealPrice": 5
                    }
                ]
            }
        ]

How do I push new object inside dishMeals in exact dishCategory ( I am providing dishCategory id, newDish object and _id of restaurant through req.body) I've tried this but nothing is changing:

     await Restaurants.updateOne(
            {
                '_id' : _id,
                'menu.dishCategory' : dishCategoryId
            },
            {
                $push : {
                    'menu.$.dishMeals' : newDish
                }
            }
        );
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  1. Use arrayFilters to filter the nested document(s) in the array field, then $push if the filter criteria in the arrayFilters met.
db.collection.update({
  "_id": _id,
  "menu.dishCategory": dishCategoryId
},
{
  $push: {
    "menu.$[menu].dishMeals": newDish
  }
},
{
  arrayFilters: [
    {
      "menu.dishCategory": dishCategoryId
    }
  ]
})

Sample Mongo Playground

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do it with arrayFilters config in update query:

db.collection.update({
  "restaurant_id": 1
},
{
  "$push": {
    "menu.$[element].dishMeals": {
      "dishMealName": "Best Burger",
      "dishMealIngredients": "Best burger in town",
      "dishMealPrice": 10
    }
  }
},
{
  "arrayFilters": [
    {
      "element.dishCategory._id": "61e6089f209b802518e2b4a4"
    }
  ]
})

Working example

about 4 years ago · Juan Pablo Isaza Denunciar

0

You may read the question and the solution they provided here, Hope this one will be helpful to you.

db.collection.update({
    "_id": 1,
    "menu.dishCategory": "61e6089f209b802518e2b4a4"
},
{
    $push: {
        "menu.$.dishMeals": newMeal
    }
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda