Monday, 10 April 2017

NodeJs with Mongoose - Nested queries async issue

I have to mongodb collections, like this:

UserGroup collection
    fields: 
        name: String
        group_id: Number
User collection
    fields:
        user_name: String
        group_id: Number

I want generate a report like this:

ADMINISTRATORS
--------------------------
jlopez
rdiaz

OPERATORS
--------------------------
amiralles
dcamponits

But I get the following report:

ADMINISTRATORS
--------------------------
OPERATORS
--------------------------
jlopez
rdiaz
amiralles
dcamponits

Following is the code to generate the report:

UserGroup.find({}, (err, groups) => {
    for(var i in groups){   
        console.log(groups[i].name)
        console.log("--------------------")
        User.find( {group_id : groups[i].group_id}, (err, users) =>{
            for(var j in users){
                console.log(users[j].user_name)
            }
        })
    }
})

Clearly, this is a problem of the NodeJs/Mongoose asynchronicity.

QUESTION: How do I make the first For cycle wait until the internal cycle ends for each UserGrop?

Thanks in advance,

David.



via David Meritano

No comments:

Post a Comment