Home > Net >  tried to push a value to an array in a loop but faced problems
tried to push a value to an array in a loop but faced problems

Time:09-02

I wanted to output users whose ids were stored in an array by looping through it and pushing the users to another array called people but neither people.push("hello") nor people.push(user) seem to have any effect on the array and the final output is just []

Quiz.findById(req.params.id, function (err,quiz) {
       if (err) { return next(err); }
       //No errors
       
       var people = [];
       var taken = quiz.taken;

       taken.forEach(id => {
           console.log(id)
           User.findById(id, function (err, user) {
               console.log(user)
               people.push(user)
               people.push("hello")
           });
       });

       res.send(people);
   });

CodePudding user response:

Can you try once once with this code?

 try {
        const quiz = await Quiz.findById(req.params.id);

        var people = [];
        var taken = quiz.taken;

        for (let i = 0; i < taken.length; i  ) {
          const user = await User.findById(taken[i]);
          people.push(user);
        }

        res.send(people);
  } catch (err) {
       console.error(err);
       return next(err);
  }
  • Related