1

I'm trying to figure out if I can make my MongoDB queries (fron Node.js) more quicker and more efficient.

Basically I have an array of "Players", each Player has a "player_id" property. I want to iterate over each Player and use the player_id to find data about the Player in a MongoDB database.

Because of the Asynchronous nature of Node.js I have to guarantee that when I send in a query to the database, the data that I get back corresponds to the player_id that was used to query.

So far I have the following code (that I simplified). What I'm most interested in is how I can achieve this without using a for loop. Thanks.

var playersArray = new Array({"player_id":1234567}, {"player_id":9847621}, {"player_id":0946783}, {"player_id":8712890});

queryDataForPlayers(playersArray, function(data){
    //Done  - Each Player now has a "new_data_property" property
})


function queryDataForPlayers(playersArray){
    var newPlayersArray = new Array();
    var counter = 0;

    for(var i=0; i<playersArray.length; i++)
    {
    retrievePlayerData(playersArray[i].player_id, playersArray[i], function(err,data)
        {
            newPlayersArray.push(data);

            if(++counter == playersArray.length)
            {   
                callback(newPlayersArray);
            }//end if
        });
    }
}


var Schema = mongoose.model('Schema');
var ObjectID = require('mongodb').ObjectID;

function retrievePlayerData(playerID, obj, callback){

    Schema.find({_id:ObjectID(String(playerID))}, function(err,data){
        obj["new_data_property"] = data;
        callback(err,obj);
    }); 
 }

2 Answers 2

2

I can't really test this, but you can pass in an array of player ID's directly to mongo, and get a document set with the related data back in just one query, something like

var playersArray = new Array({"player_id":1234567}, {"player_id":9847621}, {"player_id":0946783}, {"player_id":8712890});
var Schema       = mongoose.model('Schema');
var ObjectID     = require('mongodb').ObjectID;

function queryDataForPlayers(playersArray, callback){
    var player_ids = playersArray.map(function(player) {
        return ObjectID(String(player.player_id));
    });

    Schema.find({
        '_id': { $in: player_ids}
    }, function(err, docs){
         callback(err, docs);
    });
}
1

Use $in operator... You can use it like

Schema.find({_id:{$in:[array_of_playerid]} }).exec(function(error,results)){ }

Not the answer you're looking for? Browse other questions tagged or ask your own question.