You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从MongoDB渲染联系人列表时为何出现"Cannot read property 'id' of undefined"错误?

解决"TypeError: Cannot read property 'id' of undefined"错误

你的问题出在Express中间件的参数顺序写反了。Express路由处理函数的参数顺序是固定的:(req, res, next),但你把res放在了req前面,导致函数里的req其实是响应对象,真正的请求对象被当成了res,自然读不到req.params.id。

修正后的代码:

module.exports.getAllUsers = async (req, res, next) => {
  try {
    const users = await Users.find({ _id: { $ne: req.params.id } }).select([
      "email",
      "username",
      "avatarImage",
      "_id",
    ]);
    return res.json(users);
  } catch (ex) {
    next(ex);
  }
};

额外说明:

  • Express会严格按请求对象(req) → 响应对象(res) → 下一个中间件(next)的顺序传递参数,顺序错了就会导致变量指向错误。
  • 虽然URL里的用户ID没问题,但因为参数顺序错误,代码根本没拿到正确的请求对象,才会触发id未定义的报错。

内容的提问来源于stack exchange,提问作者David Lew

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:30:46