Express路由存在两个相同:id参数时如何获取Post的id?
问题根源
你定义的路由中两个路径参数都使用了id作为命名,Express在解析路径参数时,后出现的同名参数会覆盖之前的取值,因此req.params.id最终只会返回评论的id,无法获取到帖子的id。同时你调用findById时没有添加await关键字,异步方法返回的是Promise对象,无法直接拿到查询结果。
可行解决方案
方案1:修改路由参数命名(推荐)
将两个路径参数改为不同的名称即可分别获取两个id值,修改后的代码示例如下:
const router = require("express").Router() const Comment = require("../models/Comment") const Post = require("../models/Post"); // 调整参数名避免冲突 router.delete("/posts/:postId/comment/:commentId", async (req, res) =>{ const { postId, commentId } = req.params; // 异步查询添加await关键字 const post = await Post.findById(postId); const comment = await Comment.findById(commentId); // 后续业务逻辑 })
如果你需要的是新增评论的接口,应该使用POST请求而不是DELETE请求,参考实现如下:
// 给指定帖子新增评论的接口 router.post("/posts/:postId/comment", async (req, res) => { const { postId } = req.params; // 从请求体中获取评论内容、发布人等信息 const { content, userId } = req.body; // 创建新评论 const newComment = await Comment.create({ content, userId, postId }); // 关联评论到对应帖子 await Post.findByIdAndUpdate(postId, { $push: { comments: newComment._id } }); res.status(201).json(newComment); })
方案2:手动解析路径获取参数(不推荐)
如果不便修改路由规则,可以手动切割原始请求路径获取参数,该方案稳定性差,不建议长期使用:
router.delete("/posts/:id/comment/:id", async (req, res) =>{ // 按/切割路径,过滤空字符串后取值 const pathSegments = req.originalUrl.split('/').filter(Boolean); const postId = pathSegments[1]; // 对应posts后的第一个参数 const commentId = pathSegments[3]; // 对应comment后的第二个参数 // 后续逻辑 })
内容的提问来源于stack exchange,提问作者kinhs
相关产品推荐
相关产品推荐

