繁体   English   中英

NodeJS 和 MongoDB 中的多个查询

[英]Multiple queries in NodeJS and MongoDB

我有一个NodeJS/Express/MongoDB应用程序。 对于我的一个端点,我正在尝试从数据库中获取一些统计信息,但我在使用 Promise 时遇到了麻烦。

我知道db不会在不同的.thens之间移动,但无论我如何重新安排代码,除了第一个用户数之外,我无法从console.log()中得到任何东西。 我还尝试将 db 保存到在 function 开头声明的变量中,但这也无济于事。

以承诺的方式对MongoDB进行多次查询的正确方法是什么?

节点代码:

function getStats(num){
    var stats = "";

    MongoClient.connect(`${mongoString}/SiteUsers`)
        .then(db => {
                db.db().collection("Users").find({}).count()
                    .then( userCount => {
                        stats += `Users: ${userCount}\n`
                        return db;
                })
                .then( adminCount => {
                    db.db().collection("Users").find({admin:true}).count()
                    .then( adminCount => {
                        stats += `Admins: ${adminCount}\n`
                    })
                })
                .then( data => {
                    console.log(`Stats are now: \n${stats}`);
                })
          })
        .catch(err => {
            if(err) console.log(err);
        });

}

谢谢!

有几种方法可以处理你的 Promise 的顺序。 其中之一是使用异步/等待功能。

async function getStats(num){
    try {
      const conn = await MongoClient.connect(`${mongoString}/SiteUsers`)
      const userCount = await conn.db().collection("Users").find({}).count()
      const adminCount = await conn.db().collection("Users").find({admin:true}).count()
      console.log(`User count: ${userCount}\nAdmin count: ${adminCount}`)
    } catch (err) {
        console.log(err)
    }   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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