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, …]
2
Answers
You don’t have to call the async function inside a loop. You can simply use the $in operator to achieve the expected output.
A
forEach
does not return anything, you want to use themap
-function. That returns an array of promises, so you don’t need to add[...]
as a parameter to yourPromise.all
.You could also directly return text string in the inner function, no need to define
arrayOfGroups
upfront.