2

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.

0

1 Answer 1

2

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) { ...
Sign up to request clarification or add additional context in comments.

1 Comment

I need to extract all the posts done by a same person and throw it to the users. This is for having him the option to choose which record he need to edit and then make changes to only that . what changes i need to make if i still use find instead of findOne?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.