簡體   English   中英

類型錯誤:無法讀取未定義的屬性“推送”,我無法將注釋推送到數據數組

[英]TypeError: Cannot read property 'push' of undefined, i can't push comments to data array

我無法將評論推送到數據數組。 評論已創建(已添加到評論集)。 如何將它們推送到數據數組? 以下是我的代碼的一些屏幕截圖: Comments Schema和 , 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;

編輯:此答案假定語法錯誤是由於缺少}); camp.remove()函數之后。

不知道什么Camp的樣子,我會假定camp.create()將通過一個定義camp回調方法。 如果是這種情況,那么您似乎需要使用campground而不是camp因為新camp似乎作為campground傳遞到該回調函數中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM