简体   繁体   English

NodeJS 和 MongoDB 中的多个查询

[英]Multiple queries in NodeJS and MongoDB

I've got a NodeJS/Express/MongoDB app.我有一个NodeJS/Express/MongoDB应用程序。 For one of my endpoints I'm trying to get some stats from the database and I'm having trouble doing it using promises.对于我的一个端点,我正在尝试从数据库中获取一些统计信息,但我在使用 Promise 时遇到了麻烦。

I know that db doesn't get moved between the different .thens but no matter how I re-arrange the code I can't get anything out of the console.log() except the first users count.我知道db不会在不同的.thens之间移动,但无论我如何重新安排代码,除了第一个用户数之外,我无法从console.log()中得到任何东西。 I've also tried saving db into a variable declared at the start of the function but that doesn't help either.我还尝试将 db 保存到在 function 开头声明的变量中,但这也无济于事。

What's the proper way to make multiple queries to MongoDB in a promisified way?以承诺的方式对MongoDB进行多次查询的正确方法是什么?

Node Code:节点代码:

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

}

Thanks!谢谢!

There are several ways that you can handle the order of your promises.有几种方法可以处理你的 Promise 的顺序。 One of which is to use async/await functionality.其中之一是使用异步/等待功能。

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