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

188
Vistas
Find the document and insert value into array in MongoDB using Node.JS Mongoose

I have a mongodb collection called 'favorite' The schema for that collection is as follows:

    var favoritesSchema = new Schema({

     postedBy: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
              },
     dishes:[
             {
             type: mongoose.Schema.Types.ObjectId,
             ref: 'Dish'
             }
             ]
     },

     {timestamps:true}
     );

      var favoritesModel = mongoose.model('Favorite',favoritesSchema);

Now what I need is to find the exact document having a specific postedBy and need to insert value to the array field dishes. My code is as given below

 Favorites.find({ postedBy : req.decoded._doc._id },function(err,favorite){
       favorite.dishes.push(req.body._id);
       favorite.save(function(err,favorite)
       {
         if(err) throw err;
         console.log('favorite updated');
         res.json(favorite);
       });
     }
   });

However this is failing with TypeError: Cannot read property 'push' of undefined. Please help.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

favorite is an array of favorite documents because you're using find. You want to use findOne here instead so that favorite is the single doc you're looking to update.

Favorites.findOne({ postedBy : req.decoded._doc._id }, function(err,favorite){
    favorite.dishes.push(req.body._id);
    favorite.save(function(err,favorite) { ...
about 4 years ago · Santiago Trujillo 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