0

Is there any way to obtain the size (count) of a list of mongodb collection using the following stack : nodejs+express+mongodb+monk

I went thus far before getting lost in forest of promises.

EDIT : was on mobile stackoverflow, here's the code. Note that code below is from recalling, I didn't actually run it through node as I'am AF(P)K currently.

EDIT2 : actually adding my code now.

    // app.js
    // ...
    var express = require('express');
    // ... some more globals goes here
    var mongodb = require('monogdb');
    var monk = require('monk');
    var api = require('./routes/api');
    var db = monk('monogdb://localhost/overland');
    var app = express();

    // ....
    // shove db to every incoming request (as seen here : http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/)
    app.user(function(req,res,next){
      req.db = db;
      next();
    });
    // ready the route
    app.use('/api', api);
    // ....and the rest of the usual express-generated code goes here

...here's my route/api.js contents

    // routes/api.js
    // ...
    var express = require('express');
    var router = express.Router();

    router.get('/qstat', function(req, res){
      var db = req.db;
      var qnames = req.query.qnames ? req.query.qnames.split(',') : []; 
      console.log(qnames);
      var stats = {};
      qnames.forEach(function(qname){
          db.get(qname).count({}).then(function(doc){
          stats[qname] = doc; 
        });
      });
      res.set('Content-Type', 'application/json');
      res.send(stats);
    });

    module.exports = router;

I'm expecting that when I do this...

    curl -G http://localhost:3080/api/qstat?qnames=u3020,u3021,u3033

I'll be left with this...

    { 'u3020' : 442, 'u3021' : 143, 'u3033' : 3}

where each keys are mongo collection names and the values are their counts.

...instead I'm always left with this :

    {}

I am aware that that's not how I should deal with promises and async processes. This was intended as a quick and dirty way to gather simple statistics from some mongo collections that are used as queues at work.

bluearth
  • 501
  • 4
  • 18
  • Yes, there is a way. Using promises for various things, such as the mongodb calls, is fine. But please, try something, and if it doesn't work come back with a *specific question* regarding the *code you've written*. – Bergi Aug 14 '14 at 18:25
  • Edited my question. I was on mobile when I remembered and just have to post it immedietly before it lost me again. – bluearth Aug 15 '14 at 09:51
  • Honestly, I still want to see your actual code rather than a guess from memory written hurriedly on a phone. – wdberkeley Aug 19 '14 at 15:54
  • @wdberkeley added more info there. – bluearth Aug 20 '14 at 03:47

0 Answers0