Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!