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

如何在MongoDB中统计用户、帖子总数并传递数据到仪表盘展示

问题原因

你当前的代码同时混用了countDocuments()的回调语法和await异步等待语法,两种语法只能二选一使用,同时使用会导致await无法拿到正确的统计结果。另外代码中缺少评论数量的统计逻辑。

修复后可运行代码
app.get('/', async (req, res) => {
  try {
    // 统计用户总数
    const userCount = await User.countDocuments();
    // 统计帖子总数
    const postCount = await Post.countDocuments();
    // 统计评论总数,此处的Comment请替换为你实际使用的评论模型名称
    const commentCount = await Comment.countDocuments();

    console.log('用户数:', userCount, '帖子数:', postCount, '评论数:', commentCount);
    // 传递所有统计值到仪表盘模板
    res.render('dashboard', { userCount, postCount, commentCount });
  } catch (err) {
    console.error('统计数据出错:', err);
    res.status(500).send('数据加载失败');
  }
})
代码说明
  • 直接对模型调用countDocuments()方法即可统计对应集合的总文档数,不需要先调用find()创建查询实例
  • 移除了冗余的回调函数,仅使用await获取异步返回的统计结果,代码结构更简洁
  • 新增了统一的异常捕获逻辑,避免服务因为统计错误直接崩溃
  • 渲染模板时已经传递了三类数据的统计值,你可以直接在仪表盘模板中调用对应变量展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:48:01