【问题标题】:Get total count of collection after setting limit and offset using mongodb, mongoose and nodejs使用 mongodb、mongoose 和 nodejs 设置限制和偏移后获取收集的总数
【发布时间】:2021-03-26 18:24:31
【问题描述】:

我在 Google 上看到了关于这个主题的几个问题,但我不确定为什么其中任何一个对我有用。

我只是想通过限制和偏移传递从集合中查询数据,这似乎工作正常,但我需要一个返回总数的参数。该集合中可用的数据。

有那么难吗?我为此花费了超过 12 个小时。我一定是 Nodejs 和 mongodb 的初学者。

通过我的研究,我发现db.collection(collection_name).count())

应该返回总计数。但它显示放置它的空白对象。我再次知道它正在贬值,现在我们应该使用Collection.countDocuments or Collection.estimatedDocumentCount 。再次检查documents of mongodb。根据文件说:db.orders.countDocuments({}) 我用我的集合名称替换了订单。 db.allMinisters.countDocuments({})

我收到此错误{"error":{"message":"Cannot read property 'countDocuments' of undefined"}}。我什至使用db.collection('allMinisters').countDocuments({}),但它返回承诺并将空白对象显示为计数。

我的代码:-


    mongoose.connect( url, (err, database) => { 
        if(err) {
            return console.error(err);
        }
        db = database;

    });

    exports.getAllMinisters = (req, res, next)=>{
        console.log(db.collection('allMinisters').countDocuments({}));
        db.collection('allMinisters').find({}).skip(0).limit(10).toArray(function (err, docs) {
            if (err) {return next(err);}
              const response = {
                  count: db.collection('allMinisters').count(),
                  allMinisters: docs.map(docs=>docs),
                  status: 'success'
              }
  
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(response));
          });
      };

我如何获得总数?

【问题讨论】:

  • 使用 asyn/awaitcallback 例如。 here

标签: node.js mongodb mongoose


【解决方案1】:

我不确定您的 REST API 是什么样子,但可以试试这样的方法

exports.getallMinisters = async (req, res, next) => {
  if (req.params.docs) {
    const allMinisters = await allMinister.find({ docs: req.params.docs });

    return res.status(200).json({
      success: true,
      count: allMinisters.length,
      data: allMinisters
    });
  } else {
    //errorResponse;
  }
};

【讨论】:

    【解决方案2】:

    感谢@ashok。

    我设法通过简单地创建基于异步的函数并等待总计数查询来解决此问题。

    exports.getAllMinisters = async (req, res, next)=>{
            totalCount  = await db.collection('allMinisters').countDocuments({});
            db.collection('allMinisters').find({}).skip(0).limit(10).toArray(function (err, docs) {
                if (err) {return next(err);}
                  const response = {
                      count: totalCount,
                      allMinisters: docs.map(docs=>docs),
                      status: 'success'
                  }
      
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(response));
              });
          };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2022-01-19
      • 2016-04-28
      • 1970-01-01
      • 2013-03-29
      相关资源
      最近更新 更多