Home > Mobile >  MongoDB cursor causes my function to skip step
MongoDB cursor causes my function to skip step

Time:09-21

This is my check permission function, and it work fine, but i can't return result because function skip one step and first return "access" variable, then execute cursor function to check permission. I do not idea what i do wrong. Console logs approve that:

Console result: 1 5 return here 2 3 3 3 4

function permissionChecker(guildID, reqUserID, checkPexArray) {
    console.log("1")
    let access = false

    let pexUserCheckCursor = db.db("MainDB").collection("Permissions").find({GuildID: guildID}).toArray(function (err, result) {
        console.log("2")
        let serverDB = result[0]
        let serverPexGroups = serverDB.PexGroups
        let serverPexGroupsNames = Object.keys(serverPexGroups)

        //Object of user's pexes.
        let serverPexUsers = serverDB.PexUsers
        //Looking for at least one of required pexes.
        for (let reqPex of checkPexArray) {
            for (let pexName in serverPexUsers) {
                console.log("3")

                //If reqPex has in DB
                if (reqPex == pexName) {
                    for (let userID of serverPexUsers[pexName]) {
                        //If req user has req pex.
                        if (userID == reqUserID) {
                            console.log("4")
                            access = true
                            return

                        } else {
                            access = false
                            return
                        }
                    }
                }
            }
        }
    })
    console.log("5 return here")
}

CodePudding user response:

Your console output is correct, cause the db read is asynchronous.

Consider changing permissionChecker to an async function and then await the db callback result. Or change the permissionChecker function to return a new Promise and then resolve(access) after the loops.

  • Related