简体   繁体   中英

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. Even tried campground.markModified("comment") then campground.save(), getting the same error

//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.

As a friendly advice:

  • Switch to using promises instead of callbacks, you may set yourself up for what is known as Callback hell
  • As much as possible try not to rely on the closure nature of JavaScript and keep naming your variables the same throughout. That leads to problems like what you are experiencing now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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