I have two mongo models. The User model contains a field 'groups', which is an array and contains all the group ids that the user is a member of. The Groups model has all the information regarding the group like group name, owner etc. I want to fetch an array of all the user's groups and include details like 'group name' and 'group owner' in the response.
Please Note: I have two calls which are asynchronous. All the code below is within another post method.
//First Async Call
User.getGroupsByUsername(req.user.username, (err, groups) => {
let userGroups = [];
for (let group of groups) {
temp.group_id = group.group_id;
temp.role = group.role;
//Second Async call within for loop
User.getGroupsDetails(group_id, (err, groupInfo) => {
temp.group_name = groupInfo.name;
temp.group_owner = groupInfo.owner;
});
//temp.group_name and temp.group_owner are still unassigned because of async call
userGroups.push(temp);
temp = null;
}
res.json({
success: true,
groups: userGroups
});
});
When the code above gets to userGroups.push(temp);
userGroups
and temp
are undefined (see code comments).
I tried manipulating the queries, but mongo aggregate doesn't seem to produce results in the format I require, That would be a whole another topic. I want to know how we can produce such a response using node.js. Thanks in advance.