简体   繁体   English

使用 mongodb、mongoose 和 nodejs 设置限制和偏移后获取收集总数

[英]Get total count of collection after setting limit and offset using mongodb, mongoose and nodejs

I have seen several questions on this topic on Google but I am not sure why any of them is working for me.我在 Google 上看到了关于这个主题的几个问题,但我不确定为什么其中任何一个对我有用。

I am simply trying to query a data from collection with limit and offset passing which seems working fine but I need one more parameter where it returns the total no.我只是想通过限制和偏移传递从集合中查询数据,这似乎工作正常,但我需要一个返回总数的参数。 of data available in that collection.该集合中可用的数据。

Is it that hard?有那么难吗? I have spend over 12 hours just for this.我为此花费了超过 12 个小时。 Must be I am a beginner in Nodejs and mongodb.一定是我是 Nodejs 和 mongodb 的初学者。

With my research I found that db.collection(collection_name).count())通过我的研究,我发现db.collection(collection_name).count()) 空白返回

should return total count.应该返回总计数。 But it shows blank object where it is placed.但它显示空白 object 放置它。 I again came to know that it is being depreciated and now we should use Collection.countDocuments or Collection.estimatedDocumentCount .我再次知道它正在折旧,现在我们应该使用Collection.countDocuments or Collection.estimatedDocumentCount Again check the documents of mongodb .再次检查mongodb 的文件 As per the document it says: db.orders.countDocuments({}) where I replaced the orders with my collection name which becomes.根据它说的文件: db.orders.countDocuments({})我用我的集合名称替换了订单。 db.allMinisters.countDocuments({})

I get this error {"error":{"message":"Cannot read property 'countDocuments' of undefined"}} .我收到此错误{"error":{"message":"Cannot read property 'countDocuments' of undefined"}} I even use db.collection('allMinisters').countDocuments({}) but it return promise and display blank object as count.我什至使用db.collection('allMinisters').countDocuments({})但它返回 promise 并显示空白 object 作为计数。

My code:-我的代码:-


    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));
          });
      };

How do I get total count?我如何获得总计数?

I am not sure how your REST API looks like but try something like this我不确定你的 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;
  }
};

Thanks to @ashok.感谢@ashok。

I manage to fixed this by simply creating async based function and await the total count query.我通过简单地创建基于异步的 function 并等待总计数查询来解决此问题。

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));
          });
      };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用限制时使用 MongoDB 聚合获取总文档数 - Get a count of total documents with MongoDB aggregation when using limit 使用 mongoose 在 mongodb 中设置集合的到期时间 - Setting expiry time for a collection in mongodb using mongoose mapReduce中的猫鼬限制和总数 - Mongoose limit and total count in mapReduce 如何在Mongoose MongoDb NodeJS中的数组中获取集合中的连接对象 - How to get the connected objects within a collection in an array in Mongoose MongoDb NodeJS Mongodb - 填充项目限制并获取这些项目的总数 - Mongodb - populate with limit on items and get total count of those items 如何在nodejs中使用mongoose在没有任何文档的情况下在mongodb中创建集合 - how to create the collection in mongodb without any document using mongoose in nodejs 如何使用nodejs和mongoose从mongodb集合中删除数据 - How to remove data from mongodb collection using nodejs and mongoose 如何使用 mongoose 在 mongoDB 中使用字段计数查询集合? - How to query a collection using count of a field in mongoDB using mongoose? 如何使用nodejs在elasticsearch中获取索引的总数或总数 - How to get total count or total items of an index in elasticsearch using nodejs 使用 NodeJS 从 MongoDB 中的集合中获取数据 - get Data from a collection in MongoDB using NodeJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM