簡體   English   中英

無法使用mongoose保存到mongodb中的關聯數組

[英]Unable to save to an asssociate array in mongodb using mongoose

var mongoose = require("mongoose"),
  campground = require("./models/campground"),
  comment = require("./models/comment");

var data = [{
    name: "Offside Lake",
    image: "https://images.unsplash.com/photo-1504280390367-361c6d9f38f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
    description: "Whatever evrr"
  },
  {
    name: "Reality Check",
    image: "https://images.unsplash.com/photo-1517824806704-9040b037703b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
    description: "wabdiwyu"
  },
  {
    name: "Wawu Land",
    image: "https://images.unsplash.com/photo-1508873696983-2dfd5898f08b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
    description: "Just be feeling Wawu"
  }

];

var text = {
  text: "Hullabaloo",
  author: "Olalaa"
};
campground.comments = new Array();

function seedDB() {
  campground.deleteMany({}, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log("removed");
      data.forEach(function(camp) {
        campground.create(camp, function(err, camp) {
          if (err) {
            console.log(err);
          } else {
            console.log("Successfully added");
            comment.create(text, function(err, comment) {
              if (err) {
                console.log(err);
              } else {
                campground.comments.push(comment);
                campground.save();
                console.log("comment added");
              }
            });
          }
        });
      });
    }
  });
}

我有兩個貓鼬模特露營地和評論。 在露營地模式中,我在露營地模式中具有注釋關聯數組。 我正在嘗試向評論數組添加評論,但出現錯誤campground.save is not a function. 甚至嘗試過campground.markModified(“ comment”),然后再使用campground.save(),得到相同的錯誤

//my campground schema
var mongoose = require("mongoose");

var campSchema = new mongoose.Schema({
  name: String,
  image: String,
  description: String,
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "comment"
  }]
});

module.exports = mongoose.model("Camp", campSchema);

//my comment schema
var mongoose = require("mongoose");

var commentSchema = mongoose.Schema({
  text: String,
  author: String
})

module.exports = mongoose.model("comment", commentSchema);

如果我了解您要執行的操作,那么您將嘗試創建一個營地並將注釋放入其中。

如果是這樣,那么代碼可能看起來像這樣(將所有內容放置在一個文件中):

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});

var data = [
    {
        name: "Offside Lake",
        image: "https://images.unsplash.com/photo-1504280390367-361c6d9f38f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
        description: "Whatever evrr"
    }, {
        name: "Reality Check",
        image: "https://images.unsplash.com/photo-1517824806704-9040b037703b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
        description: "wabdiwyu"
    }, {
        name: "Wawu Land",
        image: "https://images.unsplash.com/photo-1508873696983-2dfd5898f08b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
        description: "Just be feeling Wawu"
    }
];

const comment = mongoose.model('comment', new mongoose.Schema({
    text: String,
    author: String
}));

const campground = mongoose.model('Camp', new mongoose.Schema({
    name: String,
    image: String,
    description: String,
    comments: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "comment"
    }]
}));

var text = {
    text: "Hullabaloo",
    author: "Olalaa"
};

campground.deleteMany({}, function(error) {
    if (error) {
        console.error(error);
        return;
    }

    console.log("Removed");
    data.forEach(function(camp) {
        campground.create(camp, function(error, newCamp) {
            if (error) {
                console.error(error);
                return;
            }

            console.log("Successfully added");
            comment.create(text, function(err, newComment) {
                if (err) {
                    console.error(err);
                    return;
                }

                newCamp.comments.push(newComment);
                newCamp.save();
                console.log("Comment added");
            })
        });
    })
})

問題是由於您始終使用相同的名稱,這可能使您感到有些困惑。

什么你想要做的是camp.comments.push(comment) camp.save()代替campground.comments.push(comment)campground.save()分別。

作為一個友好的建議:

  • 切換到使用Promise而不是回調,您可以為稱為回調地獄的事情做好准備
  • 盡可能不依賴JavaScript的閉包特性,並始終將變量命名為相同的名稱。 這會導致類似您現在所遇到的問題

暫無
暫無

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

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