Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

can't read push of undefined

Hello, I am struck at an error that says "can't read push of undefined ", Error is caused by line "Campgrounds.comments.push(comment)", I've talked with some people and they said that its a model, not a document blah blah, I didn't get anything. Any help would be appreciated :)

I will include Campgrounds and Comments code in comments section.

Here is the code:-

function seedDB () {
    Campgrounds.remove({},function(err){
        if (err) {
            console.log(err);
        }    
        else {
            console.log("Removed All Camping Sites!");
            data.forEach(function(seed){
                Campgrounds.create(seed,function(err){
                    if (err) {
                        console.log(err);
                    }
                    else {
                        console.log("A Campground Has Been Successfully Added!");
                        Comments.create ({
                            title:"Really Great  Place, Definately worth it.",
                            author:"Chris"
                        },function(err,comment){
                            if (err) {
                                console.log(err);
                            }
                            else {
                                Campgrounds.comments.push(comment);
                                Campgrounds.save();
                                console.log("comment added");
                            }
                        });
                    }

                });
            });
        }
    });
}

Campgrounds Schema

let campgroundSchema = new mongoose.Schema({
    name:String,
    image:String,
    description:String,
    comments: {
        type: mongoose.Schema.Types.ObjectId,
        ref:"Comments"
    }
});

Comments Schema

let commentSchema = mongoose.Schema({
    title:String,
    author:String
});

1 Answer

Steven Parker
Steven Parker
243,201 Points

This error is simply indicating that "Campgrounds" does not have an array property named "comments". The code that constructs "Comments" is not shown here, so the cause is not clear.

It's always good to show the complete code, or even better, make a snapshot of your workspace and post the link to it here. Providing a link to the relevant course page can be helpful also.