Home > other >  how to add comments to mongoose array with node and reactjs?
how to add comments to mongoose array with node and reactjs?

Time:11-10

So I am running into an issue trying to add comments to some data that is already in my mongoDB database. I want to make it so I can have comments be added and removed and updated for each account saved in my database and I am not sure what I am doing wrong necessarily. I have set up my front end to send in a new comment and all the data that needs to come along with it. it successfully gets to my back end, and at my backend it says it runs through and it gets saved but it doesnt, and when i reload the page the comments array in my data is still 0.

Account.findByIdAndUpdate(
  { _id: comment.accountId },
  {
    $push: {Account: { comments: comment }},
  },
  { new: true, upsert: true }
).exec(function (err, task) {
  if (err) {
    return res
      .status(400)
      .send({ message: "Failed to add comment due to invalid params" });
  }
  console.log("successfully uploaded comment");
  return res.status(200).send(task);
});

so here we are loading the specific account and then pushing that new comment to the comments array that is in my mongoose schema. when I take out the "Account: object and just ahve the object with comments:comment, it says there is an internal error on the back end not finding the parameter i guess, which would be comments array.

I dont know why that would be an issue. below is my mongoose schema as well.

    const AccountSchema = new Schema({
  username: {
    type: String,
  },
  name: {
    type: String,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  description: {
    type: String,
  },
  latitude: {
    type: Number,
  },
  longitude: {
    type: Number,
  },
  comments: [
    {
      id: Number,
      text: String,
      type: String,
      date: Date,
      replies: [{ id: Number, text: String, type: String, date: Date }],
    },
  ],
});

Am I not setting up my schema correctly? or am I forgetting to add something somewhere. any help would be great, thank you!

CodePudding user response:

It looks like your update query's $push specification is to blame. In the code, it says:

$push: {Account: { comments: comment }}

But your Account model does not have an "Account" field to push an object into. To insert a new element into the "comments" array, do this instead:

$push: { comments: comment }

CodePudding user response:

Just wanted to post an update, I changed around the options on the findbyidandupdate, i added new and safe and upsert all true, and then low and behold I realized that my main issue was that my comments array in my schema was set to type: string, and not array. lol thanks for the help guys.

  • Related