this is my code:
const query = await Users.findOne({_id: userId}, 'groups');
const arrayOfGroups = [];
//query.groups is an array of strings that contains id´s
await Promise.all([query.groups.forEach(async function (groupId){
const atributtesOfGroup = await Group.findById(groupId);
const {grade, group, career} = atributtesOfGroup;
arrayOfGroups.push(grade '°' group '\n' career);
})]);
i tried to find documents by an array (query.groups) of id´s and put those into the array "arrayOfGroups"
i also tried a query with $or but it didn´t work
some ideas? i just want an array with looks like this [grade '°' group '\n' career, grade '°' group '\n' career, grade '°' group '\n' career, ...]
CodePudding user response:
You don't have to call the async function inside a loop. You can simply use the $in operator to achieve the expected output.
const user = await Users.findOne({_id: userId}, 'groups').lean()
const allGroups = await Group.find({ _id: { $in: user.groups } }).lean()
const arrayOfGroups = allGroups.map((group) => `${group.grade}°${group.group}'\n'${group.career}`)
console.log(arrayOfGroups)
CodePudding user response:
A forEach
does not return anything, you want to use the map
-function. That returns an array of promises, so you don't need to add [...]
as a parameter to your Promise.all
.
You could also directly return text string in the inner function, no need to define arrayOfGroups
upfront.