aasem shoshari
aasem shoshari

Reputation: 200

Mongodb find specific comment within array of objects in post collection

i store comments in post collection like this:

...
const postSchema = new mongoose.Schema(
  {
    body: {
      type: String,
    },
    userId: {
      type: String,
      required: true,
    },
    likes: {
      type: Array,
      default: [],
    },
    img: {
      type: String,
      default: null,
    },
    comments: [
      {
        body: {
          type: String,
          required: true,
        },
        userId: {
          type: String,
          required: true,
        },
        postId: {
          type: String,
          required: true,
        },
      },
      { timestamps: true },
    ],
  },
  { timestamps: true }
);
...

i created this put route to update comment:

app.put("/update-comment", (req, res) => {
  posts.updateComment(req, res);
});

updateComment function:

const updateComment = async (req, res) => {
  try {
    const post = await Post.findById(req.body.postId);
    const comment = await post.comments.map((commentObj) => {
      return commentObj.find({ _id: req.body.commentId });
    });

    await comment.updateOne({ $set: req.body });
    res.status(200).json(comment);
  } catch (err) {
    res.status(500).json(err);
  }
};

it finds the post by postId and simply loop the comments array to find the comment object with the comment id provided, i tried this route with postman providing the following json body:

{
    "postId":"6242a4c75bce78154824fc8f",
    "commentId":"6242ac32a61fd275ed13846b",
    "body":"my first comment updated"
}

but it doesn't work, it returns 500 internal error, if i replaced the code with this:

  try {
    const post = await Post.findById(req.body.postId);
    const comment = post.comments;

    res.status(200).json(comment);
  } catch (err) {
    res.status(500).json(err);
  }

it will indeed return the comments within that post as an array of objects, i don't know what's wrong, i made sure the postId and commentId provided by the json body is correct, what's the problem?

Upvotes: 1

Views: 290

Answers (0)

Related Questions