简体   繁体   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");
              }
            });
          }
        });
      });
    }
  });
}

I have two mongoose models campground and comment. 我有两个猫鼬模特露营地和评论。 Inside the campground schema, I have the comments associative array in the campground schema. 在露营地模式中,我在露营地模式中具有注释关联数组。 I am trying to add comments to my comments array but I am getting the error - campground.save is not a function. 我正在尝试向评论数组添加评论,但出现错误campground.save is not a function. Even tried campground.markModified("comment") then campground.save(), getting the same error 甚至尝试过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);

If I understand what you are trying to do, you are trying to create a campground and place the comments inside. 如果我了解您要执行的操作,那么您将尝试创建一个营地并将注释放入其中。

If that is so, then the code may look something like this (placed everything in one file): 如果是这样,那么代码可能看起来像这样(将所有内容放置在一个文件中):

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");
            })
        });
    })
})

The problem was due to the fact that you kept the same name throughout and that might have confused you a bit. 问题是由于您始终使用相同的名称,这可能使您感到有些困惑。

What you wanted to do was camp.comments.push(comment) camp.save() instead of campground.comments.push(comment) and campground.save() respectively. 什么你想要做的是camp.comments.push(comment) camp.save()代替campground.comments.push(comment)campground.save()分别。

As a friendly advice: 作为一个友好的建议:

  • Switch to using promises instead of callbacks, you may set yourself up for what is known as Callback hell 切换到使用Promise而不是回调,您可以为称为回调地狱的事情做好准备
  • As much as possible try not to rely on the closure nature of JavaScript and keep naming your variables the same throughout. 尽可能不依赖JavaScript的闭包特性,并始终将变量命名为相同的名称。 That leads to problems like what you are experiencing now 这会导致类似您现在所遇到的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM