skip to Main Content

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


  1. 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)
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search