【问题标题】:TypeError: Cannot read property 'push' of undefined, i can't push comments to data arrayTypeError:无法读取未定义的属性“推送”,我无法将评论推送到数据数组
【发布时间】:2019-01-23 03:04:26
【问题描述】:

我无法将 cmets 推送到数据数组。 cmets 已创建(已添加到评论集合中)。如何将它们推送到数据数组?这是我的代码的一些屏幕截图:Comments Schema 和 ,The comments array is empty, Camp Schema

var mongoose = require("mongoose");
var camp = require("./models/camp");
var Comment = require("./models/comment");

var data = [
    {
        name: "Cloud's Rest", 
        image: // a link goes here
    },
    {
        name: "Desert Mesa", 
        image: //
    },
    {
        name: "Canyon Floor", 
        image: //
    }
];

function seedDB(){
   //Remove all campgrounds that existed in the database & create new campgrounds with data array.

   camp.remove({}, function(err){
        if(err){
            console.log(err);
        }
        console.log("removed campgrounds!");
         //add a few campgrounds
        data.forEach(function(seed){
            camp.create(seed, function(err, camp){
                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: "Homer"
                        }, function(err, comment){
                            if(err){
                                console.log(err);
                            } else {
                                camp.comments.push(comment);
                                camp.save();
                                console.log("Created new comment");
                            }
                        });
                }
            });
        });
    }); 
    //add a few comments
}


module.exports = seedDB;

【问题讨论】:

  • 欢迎来到 SO。如果您打算在此处发布代码,则可以考虑先删除语法错误。我们都意识到节点组件不会加载等,但错误与} 有关。现在,您似乎正在为您的变量传递campground,而不是代码中那个位置的camp
  • 是的,所以 camp.cmets 是未定义的。你没有提供任何表明它应该被定义的东西......所以......按预期工作?
  • 嗨@KevinB,不,我不这么认为。请检查我上面的架构。
  • @AnasAl-Sharif 不,错误不是谎言。它是未定义的。
  • @KevinB 我知道错误不会说谎,这就是我首先问这个问题的原因。谢谢。

标签: javascript node.js mongodb


【解决方案1】:

编辑:此答案假定语法错误是由于 camp.remove() 函数后缺少 }); 造成的。

在不知道Camp 是什么样子的情况下,我假设camp.create() 会将camp 的定义传递给回调方法。如果是这种情况,那么您似乎需要使用campground 而不是camp,因为新的camp 似乎作为campground 传递到该回调函数中。

【讨论】:

  • 嗨兰迪。很抱歉,我上面的代码中有错字,我已修复它。我还添加了我的营地模式的图片。谢谢。
  • 但是您是否将代码中的引用从 camp 更改为 campground?如果有,结果如何?
  • 嗨兰迪,是的,我更改了它,现在可以正常工作了,非常感谢您的帮助。祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 2020-04-20
  • 2017-11-23
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 2017-10-16
  • 2021-07-23
相关资源
最近更新 更多