I have just started learning the MERN stack and I am having trouble updating a text within a model. I appreciate any tips/comments!
I am working with 2 models, with the comments model embedded within the cats models like so.
const mongoose = require(“mongoose”);
const Schema = mongoose.Schema;
const commentSchema = new Schema(
{
user_id: { type: String, required: true }, cat_id: { type: String, required: true }, text: { type: String, min: [3, "Comment cannot be too short"], }, email: { type: String, required: true },
},
{ timestamps: true }
);
const Comment = mongoose.model(“Comment”, commentSchema);
module.exports = Comment;
And this is within the cat models
const mongoose = require(“mongoose”);
const Schema = mongoose.Schema;
const Comment = require("./comments.js");
const catSchema = new Schema(
{
name: { type: String, required: true, unique: true, min: [2, "Cat name minimum of 2 characters."], }, description: { type: String, required: true }, image: { type: String }, comments: [Comment.schema],
},
{ timestamps: true }
);
const Cat = mongoose.model(“Cat”, catSchema);
module.exports = Cat;
In my controller, when I update a comment, I need to update the respective comment inside the cat model too, but I’m not able to do so. I tried targeting the particular cat, foundCat, and I can’t access the comment with foundCat.comments.id(req.params.id)
Strangely enough, when I console log “foundCat.comments.id”, it tells me that this is a function? So I don’t know why I can’t access and update that text…
Here is my code:
Comment.findOne({ _id: req.params.id }, (err, comment) => {
if (err) { return res.status(404).json({ err, message: "Comment not found!", }); } console.log(req.body); // update the comment details comment.text = req.body.text; // save the updated comment comment .save() .then(() => { // return json response if successful return res.status(200).json({ success: true, id: comment._id, message: "Comment updated!", }); }) .catch((error) => { return res.status(404).json({ error, message: "Comment not updated!", }); }); // now update the comment entry for the cat too Cat.findOne({ _id: comment.cat_id }, (err, foundCat) => { console.log("This doesnt work", foundCat.comments.id(req.params.id)); foundCat.save((err, updatedCat) => { console.log(updatedCat); }); });
});
};
Example of the comments within a cat: