从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
相关产品推荐
相关产品推荐

