YelpCamp报错TypeError: 无法读取undefined的push属性
问题说明
- 预期功能:将创建的评论push到每个营地(campground)实例的comments数组中
- 故障现象:注释掉
Comment.create相关代码段(执行到console.log("created new comment")语句前)时应用可正常运行,取消注释执行到评论关联逻辑时报错
相关代码
种子函数代码
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(){ // 移除所有营地数据 Campground.remove({}, function(err){ if(err){ console.log(err); } console.log("removed campgrounds!"); // 添加初始营地数据 data.forEach(function(seed){ Campground.create(seed, function(err, campground){ if(err){ console.log(err) } else { console.log("added a campground"); // 创建关联评论 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;
Campground模型定义代码
var mongoose = require("mongoose"); // Schema定义 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);
故障原因
报错核心原因是Schema定义里的类型写法错误:Mongoose中引用ObjectId类型的正确属性是大写T开头的mongoose.Schema.Types.ObjectId,你写成了全小写的mongoose.Schema.types.ObjectId,Mongoose无法识别这个不存在的属性,执行评论关联push操作时就会抛出类型错误。
另外你贴的Desert Mesa图片链接中&和ixid之间多了一个多余空格,虽然不触发本次报错,但建议删除避免后续图片加载异常。
修复方案
修改campground.js中comments字段的type配置,将小写的types改为大写开头的Types即可,修正后的对应代码片段:
comments: [ { type: mongoose.Schema.Types.ObjectId, ref: "Comment" } ]
内容的提问来源于stack exchange,提问作者Techboy
相关产品推荐
相关产品推荐

