Sunday, 30 April 2017

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.



via Joseph T F

No comments:

Post a Comment