我正在学习nodejs,所以javascript和我在执行节点app.js时出现错误信息。我已经在搜索,但仍然没有找到我犯错的地方:/
TypeError : Cannot read property 'push' of undefined at C:...\seeds.js:46:52
这里是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;
这里是comments.js:
const mongoose = require("mongoose");
var commentSchema = mongoose.Schema({
text: String,
author: String
});
module.exports = mongoose.model("Comment", commentSchema);
这里是campground.js
const mongoose = require('mongoose');
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
});
module.exports = mongoose.model("Campground", campgroundSchema);
最后是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'));
答案 0 :(得分:0)
请在露营地架构中定义评论 var mongoose = require('mongoose');
var campgroundSchema = mongoose.Schema({ 名称:字符串, 图片:字符串, 描述:字符串, 评论: [ { type:mongoose.Schema.Types.ObjectId, 参考:'评论' } ]
}); module.exports = mongoose.model(“Campground”,campgroundSchema);
答案 1 :(得分:0)
在Web开发人员的Bootcamp课程中,我也遇到了同样的问题。 只需在campground.js文件的campgroundSchema中定义注释即可。
const mongoose = require('mongoose');
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);