Skip to content

Commit c420b76

Browse files
committed
feat: Change db query for managers to be more efficient
1 parent eee4881 commit c420b76

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

backend/controllers/user.controller.js

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ UserController.admin_list = async function (req, res) {
4444
}
4545
};
4646

47-
// Get list of Users with accessLevel 'admin' or 'superadmin' and also managed projects with GET
4847
UserController.projectManager_list = async function (req, res) {
4948
const { headers } = req;
5049

@@ -59,30 +58,32 @@ UserController.projectManager_list = async function (req, res) {
5958

6059
const updatedProjectManagers = [];
6160

61+
const allProjectIds = [
62+
...new Set(
63+
projectManagers
64+
.map((pm) => pm.managedProjects)
65+
.flat()
66+
.filter((id) => !!id),
67+
),
68+
];
69+
70+
const projects = await Project.find({ _id: { $in: allProjectIds } });
71+
72+
const projectIdToName = {};
73+
for (const project of projects) {
74+
if (project && project._id && project.name) {
75+
projectIdToName[project._id.toString()] = project.name;
76+
}
77+
}
78+
6279
for (const projectManager of projectManagers) {
6380
const projectManagerObj = projectManager.toObject();
64-
65-
/* Due to the way MongoDB searches for non-empty arrays, sometimes an empty array gets passed
66-
so we need to check if managedProjects is empty */
6781
if (projectManagerObj.managedProjects.length === 0) continue;
68-
6982
projectManagerObj.isProjectMember = true;
70-
const projectNames = [];
71-
72-
for (const projectId of projectManagerObj.managedProjects) {
73-
// using try-catch block because old user data had invalid strings (aka 'false') for ProjectIds
74-
try {
75-
const projectDetail = await Project.findById(projectId);
76-
if (projectDetail && projectDetail.name) {
77-
projectNames.push(projectDetail.name);
78-
} else {
79-
console.warn('Project detail is null, cannot access name');
80-
}
81-
} catch (error) {
82-
console.warn('Failed to fetch project details for ID:', projectId, error);
83-
}
84-
}
8583

84+
const projectNames = projectManagerObj.managedProjects
85+
.map((projectId) => projectIdToName[projectId.toString()])
86+
.filter(Boolean);
8687
if (projectNames.length) {
8788
projectManagerObj.managedProjectNames = projectNames;
8889
updatedProjectManagers.push(projectManagerObj);
@@ -244,7 +245,6 @@ UserController.signin = function (req, res) {
244245
};
245246

246247
UserController.verifySignIn = async function (req, res) {
247-
248248
let token = req.headers['x-access-token'] || req.headers['authorization'];
249249
if (token.startsWith('Bearer ')) {
250250
// Remove Bearer from string

0 commit comments

Comments
 (0)