首页 > 解决方案 > 如何解决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");
                        }
                    });
                }
            });
        });
    });
}

标签: javascriptmongodbmongoose

解决方案


您收到错误是因为露营地不包含键comments或值comments不是数组。在露营地之前记录露营地campground.comments.push(comment)以检查露营地中的“评论”是否已定义。


推荐阅读