Saturday 18 March 2017

Error Message Cannot read property 'push' of undefined

i'm learning nodejs and so javascript and i've an error message when i execute node app.js. I'm already searching but still not find where i made a mistake :/

TypeError : Cannot read property 'push' of undefined at C:...\seeds.js:46:52

Here the code of seeds.js :

const mongoose = require("mongoose");
var Campground = require("./models/campground");
var Comment = require("./models/comment");

var data = [
{
    name: "Cloud",
    image: "http://rockwoodparkcampground.com/wp-content/uploads/2015/10/campground_033.jpg",
    description: "bla bla bla"
},
{
    name: "Desert",
    image: "http://rockwoodparkcampground.com/wp-content/uploads/2015/10/campground_033.jpg",
    description: "bla bla bla"
}
]

function seedDB() {
//Remove all campgrounds
Campground.remove({}, (err) => {
    if (err) {
        console.log(err);
    }
    console.log("bla");
    // add 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 I wish there was    internet",
                        author: "Hermione Granger"
                    }, function (err, comment) {
                        if (err) {
                            console.log(err)
                        } else {
                            campground.comments.push(comment);
                            campground.save();
                            console.log("Created a new comment");
                        }
                    });
            }
        });
    });
});
}
module.exports = seedDB;

Here comments.js :

const mongoose = require("mongoose");

var commentSchema = mongoose.Schema({
text: String,
author: String
});

module.exports = mongoose.model("Comment", commentSchema);

Here campground.js

const mongoose = require('mongoose');

var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
});
module.exports = mongoose.model("Campground", campgroundSchema);

And finally the top of app.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var Campground = require("./models/campground");
var seedDB = require("./seeds")
seedDB();

mongoose.connect('mongodb://localhost/beer_n_camp');
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/views'));



via Pierre Jones

No comments:

Post a Comment