MEAN栈用estimatedDocumentCount获取关注列表仅返回计数无用户数据如何解决
MEAN栈已关注用户列表接口返回无用户详情问题修复
我正在使用MEAN栈开发一款社交媒体应用,需要实现已关注用户列表功能。由于Collections.Find()已被弃用,我采用Collections.estimatedDocumentCount()来获取用户列表并返回JSON格式数据,目前正通过Postman进行测试。
当前接口可以正常返回用户总数和关注数量,但返回的JSON中没有其他可展示的用户数据。
原实现代码如下:
function getFollowTest(req,res){ var userId = req.user.sub; if (req.params.id) { user.id = req.params.id; } var page = 1; if (req.params.page) { page = req.params.page; } var itemsPerPage = 4; Follow.estimatedDocumentCount({user:userId}) .populate({path: 'followed'}) .paginate(page, itemsPerPage, (err, follows, total)=>{ if (err) return res.status(500).send({message:'Server error'}); if (!follows) return res.status(404).send({message:'you are not following any user'}); res.status(200).send({ total: total, pages: Math.ceil(total/itemsPerPage), follows }); }); }
原Postman返回结果:
问题根因
你误用了estimatedDocumentCount()方法,该方法仅用于统计集合文档总数,返回的是数值结果,并非可查询的文档游标,无法链式调用populate()关联查询关注用户详情,也不支持分页调用。你提到的Collections.Find()被弃用是对MongoDB旧驱动API和Mongoose API的混淆,Model.find()在Mongoose中一直是正常可用的查询方法。
修复后代码
function getFollowTest(req,res){ let userId = req.user.sub; if (req.params.id) { userId = req.params.id; // 修复原代码未定义的user.id变量问题 } const page = parseInt(req.params.page) || 1; const itemsPerPage = 4; const skip = (page - 1) * itemsPerPage; // 并行查询总数和列表提升性能 Promise.all([ Follow.countDocuments({user: userId}), Follow.find({user: userId}) .populate('followed') .skip(skip) .limit(itemsPerPage) ]).then(([total, follows]) => { if (follows.length === 0) { return res.status(404).send({message:'你还没有关注任何用户'}); } res.status(200).send({ total, pages: Math.ceil(total/itemsPerPage), follows }); }).catch(() => { return res.status(500).send({message:'服务端错误'}); }) }
优化说明
- 对page参数做了数值转换和默认值处理,避免字符串类型导致分页计算错误
- 改用Promise.all并行执行总数统计和列表查询,接口响应速度更快
- 优化了空列表判断逻辑,兼容无关注记录的场景
内容的提问来源于stack exchange,提问作者SecaidaDevStudent
相关产品推荐
相关产品推荐

