You need to enable JavaScript to run this app. Express校验评论归属用户ID的中间件功能失效,请问是什么原因?
优惠活动
大模型
产品
解决方案
定价
更多

Express校验评论归属用户ID的中间件功能失效,请问是什么原因?

问题根因

MongoDB 返回的 postedBy._id 是 Mongoose 内置的 ObjectId 类型对象,而你从请求头获取的 userId 是字符串类型。=== 是严格相等判断,要求值和类型完全一致,所以哪怕控制台打印出来的文本内容完全相同,类型不同的情况下判断结果永远为 false。

修复方案

任选以下任意一种修改判断逻辑即可:

  1. 将 ObjectId 转为字符串后比较
if(userId === postedById.postedBy._id.toString()) {
  next()
  return
}
  1. 用 Mongoose 内置的 equals() 方法判断(更推荐,避免字符串转换异常)
if(postedById.postedBy._id.equals(userId)) {
  next()
  return
}

额外优化建议

  • 新增评论存在性判断,如果传入的 commentId 不存在,查询结果为 null 时直接访问 postedById.postedBy 会抛出异常
  • 给变量加上 const/let 声明,避免全局变量污染
  • 错误返回加上对应 HTTP 状态码,更符合接口规范
  • 查询时可以仅指定返回 postedBy 字段,降低数据库查询开销

优化后的中间件参考:

const Comment = require('../models/Comment');

module.exports.verfyUserIdPostedBy = async function (req, res, next) {
  try {
    const userId = req.header('userId')
    const comment = await Comment.findById(req.params.commentId, 'postedBy');
    if (!comment) {
      return res.status(404).send('评论不存在')
    }
    if(comment.postedBy._id.equals(userId)) {
      next()
      return
    }
    res.status(403).send('Forbidden')
  } catch (err) {
    res.status(500).json({message: err})
  }
}

内容的提问来源于stack exchange,提问作者Mario Chacon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 07:24:07