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

使用Mongoose获取集合全部文档数量返回多余信息如何解决

问题原因

Mongoose的countDocuments()是异步API,直接调用返回的是Mongoose Query实例对象,不是统计结果,所以你打印出来才会看到一堆查询相关的内置参数,而不是预期的数字。

正确实现方案

方案1:async/await 写法(最推荐)

需要在异步函数中使用await等待查询完成:

// 注意:该代码需要放在异步函数内部执行
const getTotalCount = async () => {
  const total = await ServicesModel.countDocuments({});
  console.log(total); // 这里输出的就是数字类型的总文档数
  return total;
}
getTotalCount();

如果你是要做精确的条件统计,用countDocuments()没问题;如果只是要整个集合的大概总数(不需要过滤条件、允许极微小误差,性能更高),可以用专门的estimatedDocumentCount()方法:

const total = await ServicesModel.estimatedDocumentCount();

方案2:回调函数写法

如果不想用async/await,也可以传入回调函数获取结果:

ServicesModel.countDocuments({}, (err, total) => {
  if (err) {
    // 自行处理错误逻辑
    console.error('统计失败:', err);
    return;
  }
  console.log(total); // 这里拿到总文档数
});

方案3:Promise.then 写法

也可以直接用Query实例自带的then方法链式调用:

ServicesModel.countDocuments({})
  .then(total => {
    console.log(total);
  })
  .catch(err => {
    console.error('统计失败:', err);
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 01:54:03