You need to create a scope that captures the current value of i
because by the time your findOne()
callbacks execute, the loop has already long been finished and i=team.length
. You're also sending the response before any of the names are filled in. You may want to use the async
module to handle this for you.
This:
for(var i = 0; i < team.length; i++){
members[i] = {};
members[i].accountID = team[i].accountID;
members[i].status = team[i].status;
Accounts.findOne(
{ _id : mongojs.ObjectId(team[i].accountID) },
function(error, doc){
/// The following line produces the error:
/// 'Cannot set property name of undefined'
members[i].name = doc.name;
}
);
}
response.send(members);
Becomes:
var async = require('async');
// ....
async.each(team, function(teamItem, callback) {
var member = {
accountID: teamItem.accountID,
status: teamItem.status,
name: ''
};
members.push(member);
Accounts.findOne(
{ _id : mongojs.ObjectId(member.accountID) },
function(error, doc) {
if (error)
callback(error);
else {
member.name = doc.name;
callback();
}
}
);
}, function(err) {
if (err)
response.send(500, err.toString());
else
response.send(members);
});