简体   繁体   中英

Multiple queries in NodeJS and MongoDB

I've got a NodeJS/Express/MongoDB app. For one of my endpoints I'm trying to get some stats from the database and I'm having trouble doing it using promises.

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. I've also tried saving db into a variable declared at the start of the function but that doesn't help either.

What's the proper way to make multiple queries to MongoDB in a promisified way?

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

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