node.jsexpressmongoosemongoose-web-server

How to run multiple mongoose queries at once and generate json respnose using expressjs


In this code I'm trying to get object counts from two different documents and send one json response with results from both quires. but unfortunately response of this code segment is always -1 it won't get updated with query results.

  router.get('/stats', function (req, res, next) {
  let cateCount = -1;
  let userCount = -1;
    Category.find({}).then(function(item){
    cateCount = item.length;
    });
    Register.find({}).then(function(item){
      userCount = item.length;
    });

  res.json({
    "categories": 
      cateCount,
    "users":
    userCount
  });

response :

{"categories":-1,"users":-1}

Solution

  • to count documents use : https://mongoosejs.com/docs/api/model.html#model_Model.count

    and async-await this way :

     router.get('/stats',async function (req, res, next) {
      let cateCount = -1;
      let userCount = -1;
        cateCount = await Category.count({});
        userCount = await Register.count({});
        res.json({
          categories:cateCount,
          users:userCount
       });
    });