【问题标题】:How to get number of documents by using find method express js?如何使用 find 方法 express js 获取文档数量?
【发布时间】:2019-11-11 17:04:53
【问题描述】:

如何获取文件数 find total express js?我在谷歌和 StackOverflow 中搜索过。但我找不到。人们说的是使用countDocuments 来获取模型的文档数量,如下所示:

UserModel.countDocuments(function(err,count){ 
  count
  res.render('index',{count:count}); // returning count and rendering to index.ejs
});

但我想要同时得到结果集和recordcount,如下所示

UserModel.find(function(err,data){
    res.render('index',{data:data,count:data.count});
});

【问题讨论】:

  • data 是一个数组,所以 data.length 可以工作

标签: node.js express mongoose


【解决方案1】:
UserModel.find({}, null, options).exec().then(data => {
        UserModel.count({}, (err, counts) => {
            if (err) {
                           res.send(err)

            } else {
                res.render('index',{data:data,count:data.counts});

            }
        })
    }).catch(err => {
           res.send(err)
    });

【讨论】:

  • 您尝试调用 UserModel 2 次。一个用于获取所有记录,另一个用于计数。是否有任何其他解决方案可以在一次调用中同时获取数据和计数。
  • 仅是单个api调用,usermodel是所有的表名
  • 是的,工作正常。这是唯一的方法和正确的方法吗? .我已经编写了以下代码,并且工作正常。这是提取数据的好方法吗? User.find().then(UserData => { User.countDocuments().then(UserCount=>{ Category.find().then(CategoryData=>{ Category.countDocuments(). res.render('index', {categoryCount:CategoryCount,userCount:UserCount,userData:UserData,CategoryData:CategoryData}); }); }); });
  • 它会起作用,但它似乎有点多余。 UserModel.find() 返回一个数组,所以你可以继续运行:res.render('index',{data:data,count:data.length});
  • 超级!。非常感谢海豹拉波莱。这就是我想要的。 :)
【解决方案2】:

由于UserModel.find() 返回一个数组,您可以只返回来自data.length 的计数。

另外,请注意 Model.count() 在最新的 mongoose 版本 (v5.7.6) 中已被弃用。如果你坚持使用它或类似的东西,你可以使用以下之一:

  • Model.estimatedDocumentCount()(快速):它使用集合的元数据为您提供文档数量的估计see docs
  • Model.countDocuments()(对于大型集合可能会很慢):为了更准确的计数。 see docs

【讨论】:

    【解决方案3】:

    UserModel.find() 返回一个数组,所以你可以继续运行: res.render('index',{data:data,count:data.length});

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 2015-06-14
      • 2019-02-25
      • 2023-01-03
      • 2020-01-22
      • 2014-01-27
      • 1970-01-01
      相关资源
      最近更新 更多