Why this yelpcamp code returned "TypeError: Cannot read properties of undefined (reading 'push')"

227 Views Asked by At

I am just a student in webdev,I already try to correct it but fail, I appreciate if exprienced members here can assist me in correcting this error, the code suppose to push the comment to every campground array available. The app run if I comment out comment.create part(up to console.log("created new comment"). Kindly refer to image for the error message. Thank you

var mongoose = require("mongoose");
var Campground = require("./models/campground");
var Comment   = require("./models/comment");
var data = [
   {
      name: "Cloud's Rest", 
      image: "https://farm4.staticflickr.com/3795/10131087094_c1c0a1c859.jpg",
      description: "blah blah blah"
},
  {
     name: "Desert Mesa", 
    image: "https://images.unsplash.com/photo-1557214997-7eae7e0e7aaa?ixlib=rb-1.2.1&  ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8ZGVzZXJ0JTIwbWVzYXxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60",
    description: "blah blah blah"
},
{
    name: "Canyon Floor", 
    image: "https://farm1.staticflickr.com/189/493046463_841a18169e.jpg",
    description: "blah blah blah"
}
]
function seedDB(){
 //Remove all campgrounds
    Campground.remove({}, function(err){
        if(err){
        console.log(err);
        }
    console.log("removed campgrounds!");
     //add a few campgrounds
    data.forEach(function(seed){
        Campground.create(seed, function(err, campground){
            if(err){
                console.log(err)
            } else {
                console.log("added a campground");
               // create a comment
                Comment.create(
                    {
                        text: "This place is great, but facilities are not good",
                        author: "John Paul"
                     }, function(err, comment){
                          if(err){
                              console.log(err);
                          } else {
                              campground.comments.push(comment);
                              campground.save();
                              console.log("Created new comment");
                          }
                      });   
              }
        });
    });
}); 
   }
module.exports = seedDB;

ErrorMessage: ErrorMessage

@Haris: kindly check campground.js below, I guess the comments array is defined

var mongoose = require("mongoose");

//Schema Setup var campgroundSchema = new mongoose.Schema({ name: String, image: String, description: String, comments: [ { type: mongoose.Schema.types.ObjectId, ref: "Comment" } ] });

module.exports = mongoose.model("Campground", campgroundSchema);

1

There are 1 best solutions below

1
Haris Bouchlis On

You are trying to push in an array that is undefined, problem occurs in this line

campground.comments.push(comment);

You have to check if the campground.comments array exists before pushing, and initialize it in case its undefined