How to get data from mongoose find query inside for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yogeshkr
    New Member
    • Oct 2022
    • 1

    How to get data from mongoose find query inside for loop

    i cant figure out how to get when i have to find the all records in the mongo db document and check a field which is true or false from each document inside collection

    here i am first finding all user from user table after that taking the user ids and finding teir course registrations if the course registration is true then i have to increase cnt by one my question is how can i get the final cnt value outside of for loop
    Code:
           countuser(){
           let cnt=0;
           for(let i=0;i<users.length;i++)
            {
               this.course_reg.find({_id:userId[i]},function(error,coursereg){
                   
                          if(coursereg.isCompleted==true)
                           {
                                     // it will count the user who have isCompleted is true
                                        cnt++;
                            }
               })
    }
  • zmbd
    Recognized Expert Moderator Expert
    • Mar 2012
    • 5501

    #2
    the variable cnt should have your loop count, no?
    However, you don't mention what you want to do with the value; thus, something simple like console.log(cnt ) should send the value to the console

    Comment

    Working...