删除帖子评论失败?

问题描述 投票:0回答:1

我在控制器中正确执行了该功能(正如我所想),但即使邮递员返回响应“评论已成功删除!”,我也无法删除评论。

去数据库发现该评论存在数据库中,并且没有被删除。

我想知道代码有什么问题。它使得删除过程没有按应有的方式完成。

评论路线

router.delete("/:id/comment/:cid", protectRoute, deleteComment);

控制器

const deleteComment = async(req, res) => {
try {
    const post = await Post.findById(req.params.id);

    const comment = post.comments.find(
        (comment) => comment._id.toString() === req.params.cid.toString()
    );

    if(!comment){
        return res.status(404).json({ error: "Comment not found!" });
    }

    if(comment.userId.toString() !== req.user._id.toString()){
        return res.status(401).json({ error: "Unauthorized to delete comment" });
    }

    if (comment.userId.toString() === req.user._id.toString()) {
        post.comments = post.comments.filter(
            ({ id }) => id !== req.params.cid
        );
    }
        await post.save();
    
        return res.status(200).json({ message: "Comment deleted successfully!" });
} catch (err) {
    res.status(500).json({ error: err.message });
}

};

我的帖子模型

import mongoose from "mongoose";
const ObjectId = mongoose.Types.ObjectId;

const postSchema = mongoose.Schema({
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    text: {
        type: String,
        maxLength: 500
    },
    img: {
        type: String,
    },
    video: {
        type: String,
        ref: "Upload"
    },
    likes: [{
        // array of user id's
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        default: []
    }],
    saves: [{
        // array of user id's
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
        default: []
    }],
    comments: [
        {
            id: {
                type: ObjectId,
            },
            userId: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User",
                required: true
            },
            text: {
                type: String,
                required: true
            },
            likes: [{
                // array of user id's
                type: mongoose.Schema.Types.ObjectId,
                ref: "User",
                default: []
            }],
            userProfilePic: {
                type: String,
            },
            username: {
                type: String
            },
            date: {
                type: Date,
                default: Date.now()
            },
            replies: [{
                id: {
                    type: ObjectId,
                },
                userId: {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: "User",
                    required: true
                },
                text: {
                    type: String,
                    required: true
                },
                userProfilePic: {
                    type: String,
                },
                username: {
                    type: String
                },
                date: {
                    type: Date,
                    default: Date.now()
                }
            }]
        }
    ]
}, {timestamps: true}
)

const Post = mongoose.model('Post', postSchema);

export default Post;
javascript reactjs node.js mongodb mongoose-schema
1个回答
0
投票

您在过滤器函数中使用了 id,但注释数组中的实际属性名称是 _id。此外,您似乎正在使用严格相等 (===) 来比较 ID,这可能无法按预期工作,因为一个是 ObjectId,另一个是字符串,请尝试以下代码:-

const deleteComment = async (req, res) => {
    try {
        const post = await Post.findById(req.params.id);

        const commentIndex = post.comments.findIndex(
            (comment) => comment._id.toString() === req.params.cid.toString()
        );

        if (commentIndex === -1) {
            return res.status(404).json({ error: "Comment not found!" });
        }

        if (post.comments[commentIndex].userId.toString() !== req.user._id.toString()) {
            return res.status(401).json({ error: "Unauthorized to delete comment" });
        }

        post.comments.splice(commentIndex, 1); // Remove the comment at commentIndex
        await post.save();

        return res.status(200).json({ message: "Comment deleted successfully!" });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.