当前位置: 代码迷 >> JavaScript >> 无法使用mongoose保存到mongodb中的关联数组
  详细解决方案

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

热度:49   发布时间:2023-06-05 09:33:53.0
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的闭包特性,并始终将变量命名为相同的名称。 这会导致类似您现在所遇到的问题
  相关解决方案