【问题标题】:NodeJS/MongoDB. Async/await returns the whole array of dataNodeJS/MongoDB。异步/等待返回整个数据数组
【发布时间】:2018-04-12 10:22:23
【问题描述】:

所以,我试图理解为什么在 MongoDB 的情况下 Async/await 返回一些奇怪的结果,而不是条件 nedded?

例如:我尝试从await User.find() 获取req.session.userId,但总是获取用户数组。

我的代码:

.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...
})

【问题讨论】:

  • 完全不清楚您要做什么。 req.session.userIdreq 对象上的东西,而不是你数据库中的东西。此外,从回调中返回的东西不一定会成为原始函数的返回值。
  • 感谢您的帮助!我刚从 mongo 开始,并在不久前表达。 @Mark_M

标签: javascript node.js mongodb async-await


【解决方案1】:

你必须await userFind() 函数。

异步函数的工作方式是它们返回一个承诺。您正在等待 userFind() 内部的数据库访问,但您不是在等待 userFind() 本身。

.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...
})

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2020-09-23
    • 2021-04-03
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多