Mongoose update subdocument

Viewed 87

I have some posts documents which contains an array of ids of comments. I am trying to update a particular comment based on the post and the comment id and not sure how to go about it. I have tried to use the $set command but I think I missed something and It doesn't work. What I have tried doing.

async function updateComment(req, res){
try{
    const post = await PostsModel.findOneAndUpdate(
        {"postID": req.params.id, "comments.id": req.params.commentID},
        {"$set": {
            "comments.$": req.body
            }}
    ).populate("comments");

    if (!post){
        return res.status(404).json({msg: "No post found"});
    }

    res.status(200).json({post});
}catch (e) {
    res.status(500).json(e.message);
}

}

The structure and schema of the document:

{
            "_id": "62b2c3d0e88f58ddd1135bc7",
            "title": "aaaa",
            "content": "check it out",
            "createdAt": "2022-06-22T07:23:34.525Z",
            "comments": [
                "62b2fe23b15d50b496149128"
            ],
            "postID": 1
        }

The schema for both the post and comment:

const CommentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },
    content:{
        type: String,
        required: true
    },
    createdAt:{
        type: Date,
        default: new Date()
    },
})
const PostsSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    createdAt:{
        type: Date,
        default: new Date()
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Comment"
        }
    ]

});
0 Answers
Related