Multiple mongoose count() queries to a MongoDB

Viewed 3845

first: me -> MongoNoob and I know this has already been asked in one or the other way, but I haven't found anything specific until now. Let's say I have two Moongoose Models described like this:

var pollSchema = mongoose.Schema({
    title: String,
    choices: [{
        content: String
    }]
});
var choiceSchema = mongoose.Schema({
    poll_id: mongoose.Schema.ObjectId,
    option: Number
});

A UI shows the poll and when a user selects a choice, it is written into the choiceSchemamodel. Now I would like to create a 'statistic', telling me how many users selected option 1, option 2, option 3,.... I could simply fetch all choices for a poll with find and generate the statistic in server code, but if I had a million user choices, I would have to deal with an array of the same size. This cannot be right. I could however generate a query and use the count()method:

var query = Choice.find({poll_id: someId}),
query.where('option', 1);
var resultForOption1;
query.count(function(err, count)) {
    resultForOption1 = count;
});

How would I do this for multiple options and 'join' (haha) the results into an array? Since this is all asynchronous I would have nest the calls, but that is not an option for a variable number of queries.

Do I miss the wood for the trees :-)? Can somebody point me in the right direction?

BR, Daniel

2 Answers
Related