1

How to make many counts using an array as input in Mongoose, and return an array

I am trying to use the code below but it is not working, list2 is returning as empty.

list = ['Ann', 'Bob', 'John', 'Karl'];
list2 = [];

for(let i = 0; i < list.length; i++) {
    Clients.count({name: list[i]}, function(err, doc){
        list2.push(doc);
    })
}
return list2
2
  • Clients.count() is an asynchronous function. return list2 will be executed before all the db queries are completed, so that count in list2 will not accurate when you consume it. You better learn how to handle asynchronous code via callbacks or promises. Commented Jan 21, 2017 at 16:17
  • If you get the data in form of array of objects like this [ {name:'Ann',Count:1},{name:'Bob',Count:3},{name:'John',Count:5} ], Will that be ok for you? Commented Jan 21, 2017 at 16:21

3 Answers 3

3

You could run an aggregation pipeline as follows:

list = ['Ann', 'Bob', 'John', 'Karl'];
list2 = [];
Clients.aggregate([
    { "$match": { "name": { "$in": list } } },
    {
        "$group": {
            "_id": "$name",
            "count": { "$sum": 1 }
        }
    },
    {
        "$group": {
            "_id": null,
            "list2": {
                "$push": {
                    "name": "$_id",
                    "count": "$count"
                }
            }
        }
    }
]).exec(function(err, results) {
    list2 = results[0].list2;
    console.log(list2);
});
Sign up to request clarification or add additional context in comments.

Comments

2
const async = require('async');

var list = ['Ann', 'Bob', 'John', 'Karl'];

async.map(list, function(item, callback) {
    result = {};
    Clients.count({name: item}, function(err, data) {
        result[item] = data || 0;
        return callback(null, result);
    });
}, function(err, data) {
    console.log(data);
});

Comments

0

Here's another way based on Med Lazhari's answer

const async = require('async');

var list = ['Ann', 'Bob', 'John', 'Karl'];

var counting = function (item, doneCallback) {
    var query = Clients.count({name: item});
    query.then(function (doc) {
      return doneCallback(null, doc);
    });  
  };

async.map(list, counting, function(err, data) {
    console.log(data);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.