javascript - 如何解决typeError,猫鼬?
问题描述
我收到以下代码的 typeError 。数据数组是在这个函数seedDB之前创建的。
TypeError: Cannot read property 'push' of undefined
这是代码:
function seedDB() {
Campground.deleteMany({}, function(err, res){
if(err) {
console.log(err);
} else {
console.log("removed campgrounds");
}
data.forEach(function(seed) {
Campground.create(seed, function(err, campground) {
if(err) {
console.log(err);
} else {
console.log("added a new campground");
Comment.create(
{
text: "this place is great",
author: "Homer"
}, function(err, comment) {
if(err) {
console.log(err);
} else {
//it is this line here....=>
campground.comments.push(comment);
campground.save();
console.log("created new comment");
}
});
}
});
});
});
}
解决方案
您收到错误是因为露营地不包含键comments
或值comments
不是数组。在露营地之前记录露营地campground.comments.push(comment)
以检查露营地中的“评论”是否已定义。
推荐阅读
- django - 如何使用本地 yml 模式文件将 Redoc 文档添加到 Django?
- .net-core - .NET CORE - 当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头不能是通配符“*”
- css - @media (prefers-color-scheme: light) 在 chrome 中不起作用
- java - 如何为自定义 api 错误消息解决此错误。如果我删除了此类的两个方法,则项目运行没有错误
- jquery - 将模型传递给 jQuery
- reactjs - “是的”验证库无法在 TypeScript 中编译
- google-cloud-platform - AttributeError:“StreamExhausted”对象没有属性“消息”。流中的字节数不足;预计1265662718,
- java - 程序直接进入else语句
- node.js - 如何使用 express-oauth-server 进行身份验证?
- r - 如何跨多个列匹配列并在新列中返回匹配的 col_name