无法使用mongoose保存到mongodb中的关联数组

时间:2019-02-21 11:05:35

标签: javascript 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);

1 个答案:

答案 0 :(得分:0)

如果我了解您要做什么,那么您将尝试创建一个营地并将评论放入其中。

如果是这样,那么代码可能看起来像这样(将所有内容放置在一个文件中):

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而不是回调,您可以将自己设置为Callback hell
  • 尽可能避免不依赖JavaScript的闭包性质,并始终将变量命名为相同的名称。这会导致出现诸如您现在正在经历的问题