diff --git a/app/data/allocations-dao.js b/app/data/allocations-dao.js index 24d4718c4a..dbe883f112 100644 --- a/app/data/allocations-dao.js +++ b/app/data/allocations-dao.js @@ -87,24 +87,24 @@ const AllocationsDAO = function(db){ if (err) return callback(err, null); if (!allocations.length) return callback("ERROR: No allocations found for the user", null); - let doneCounter = 0; - const userAllocations = []; + const userIds = allocations.map(alloc => alloc.userId); - allocations.forEach( alloc => { - userDAO.getUserById(alloc.userId, (err, user) => { - if (err) return callback(err, null); - - alloc.userName = user.userName; - alloc.firstName = user.firstName; - alloc.lastName = user.lastName; + userDAO.getUsersByIds(userIds, (err, users) => { + if (err) return callback(err, null); - doneCounter += 1; - userAllocations.push(alloc); + const usersById = {}; + users.forEach(user => { usersById[user._id] = user; }); - if (doneCounter === allocations.length) { - callback(null, userAllocations); + allocations.forEach(alloc => { + const user = usersById[parseInt(alloc.userId)]; + if (user) { + alloc.userName = user.userName; + alloc.firstName = user.firstName; + alloc.lastName = user.lastName; } }); + + callback(null, allocations); }); }); }; diff --git a/app/data/user-dao.js b/app/data/user-dao.js index a674363efa..d080169a6b 100644 --- a/app/data/user-dao.js +++ b/app/data/user-dao.js @@ -100,6 +100,13 @@ function UserDAO(db) { }, callback); }; + this.getUsersByIds = (userIds, callback) => { + const parsedIds = [...new Set(userIds.map(id => parseInt(id)))]; + usersCol.find({ + _id: { $in: parsedIds } + }).toArray(callback); + }; + this.getUserByUserName = (userName, callback) => { usersCol.findOne({ userName: userName