gpt4 book ai didi

javascript - 错误信息 无法读取未定义的属性 'push'

转载 作者:太空宇宙 更新时间:2023-11-04 02:09:32 25 4
gpt4 key购买 nike

我正在学习nodejs和javascript,当我执行node 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'));

最佳答案

请在露营地架构中定义注释var mongoose = require('mongoose');

var CampgroundSchema=mongoose.Schema({ 名称:字符串, 图像:字符串, 描述:字符串, 评论: [ { 类型:mongoose.Schema.Types.ObjectId, 引用:“评论” } ]

});module.exports =mongoose.model("营地",campgroundSchema);

关于javascript - 错误信息 无法读取未定义的属性 'push',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com