简体   繁体   中英

NodeJS/MongoDB. Async/await returns the whole array of data

So, I try to understand why the Async/await in case of MongoDB returns some strange result, instead of the nedded by the condidtion?

For example: I try to get the req.session.userId from await User.find() , but always get the array of Users.

My code:

.get((req, res) => {
        let a = '';
        async function userFind() {
            const sess = await User.find((err, users) => {
                if (req.session.userId !== undefined) {
                    return req.session.userId; // return the all array ou Users, instead of just session value
                } 
                else {
                    return "req.session.userId"; // return the all array of Users, instead of just a string
                }
            });
            console.log(sess);

            const empl =  await EmployersSchemaDB.find((err, employers) => {
                return employers; 
            });

            return {
                sess, 
                empl
            }
        }   
        console.log(userFind()); // gives two arrays of data above together, but not that I want...
})

You have to await the userFind() function.

The way async functions work is that they return a promise. You are awaiting the DB accesses inside of userFind() but you are not awaiting userFind() itself.

.get(async (req, res) => {
        let a = '';
        async function userFind() {
            const sess = await User.find((err, users) => {
                if (req.session.userId !== undefined) {
                    return req.session.userId; // return the all array ou Users, instead of just session value
                } 
                else {
                    return "req.session.userId"; // return the all array of Users, instead of just a string
                }
            });
            console.log(sess);

            const empl =  await EmployersSchemaDB.find((err, employers) => {
                return employers; 
            });

            return {
                sess, 
                empl
            }
        }   
        console.log(await userFind()); // gives two arrays of data above together, but not that I want...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM