我正确地完成了控制器中的功能(正如我所认为的),但是我无法删除 comments ,即使postman 返回响应" comments 删除成功!"

当我转到数据库时,我发现该 comments 存在于数据库中,并且没有被删除.

我想知道代码出了什么问题.这使得删除过程没有按应有的方式进行.

comment route

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

controller

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 });
}

};

my Post Model

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;

推荐答案

这是一个常见的操作,通常使用简单的findOneAndUpdate来完成,如下所示:

const deleteComment = async(req, res) => {
   try{
       const post = await Post.findOneAndUpdate(
           {
               _id: req.params.id, //< Match the Post._id
               comments: { //< Must also match comments._id and comments.userId 
                   $elemMatch: {
                       _id: req.params.cid,
                       userId: req.user._id
                   }
               }
           },
           {
               $pull: {
                   'comments': {_id: req.params.cid}, //< Remove the comment from array
               }
           },
           { new : true } //< Return the updated document after the comment removed
       );
       if(!post){ //< Will return null of no document matches
           return res.status(400).json({
               error: "Comment not found!"
           });
       }
       return res.status(200).json({
           message: "Comment deleted successfully!"
       });
   } catch(err){
       console.log(err);
       res.status(500).json({
           error: err.message
       });
   }
}

Edit:我刚注意到你也在查userId,所以你需要用$elemMatch.

Javascript相关问答推荐

React Hooks中useState的同步问题

主要内部的ExtJS多个子应用程序

使用print This时, map 容器已在LeafletJS中初始化

类型脚本中只有字符串或数字键而不是符号键的对象

Chart.js V4切换图表中的每个条,同时每个条下有不同的标签.怎么做?

基于变量切换隐藏文本

使用Google API无法进行Web抓取

禁用.js文件扩展名并从目录导入隐式根index.js时,找不到NodeJS导入模块

与svg相反;S getPointAtLength(D)-我想要getLengthAtPoint(x,y)

AddEventListner,按键事件不工作

有没有一种直接的方法可以深度嵌套在一个JavaScript对象中?

如何通过Axios在GraphQL查询中发送数组

与在编剧中具有动态价值的定位器交互

为什么我不能使用其同级元素调用和更新子元素?

使用createBrowserRoutVS BrowserRouter的Reaction路由

如何正确地在ComponentWillUnmount中卸载状态以避免内存泄漏?

在高位图中显示每个y轴系列的多个值

为什么当雪碧的S在另一个函数中时,Phaser不能加载它?

React数组查找不读取变量

在执行console.log(new X())时记录一个字符串