Reputation: 801
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.
Upvotes: 2
Views: 1660
Reputation: 311855
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) { ...
Upvotes: 2