-1

I wanted to close my mongodb client whenever I'm done operations as my connection limits keep reaching 100. But whenever I close my connection, I get this error:

MongoError: Topology was destroyed

My Code:

test.js - The JS file that will be executed

const db = require('./dbNew')

  db.checkUserID(124214).then(function(result){
       if(result == false){
           db.getAccessToken(810191770).then(function(result2){
                console.log(result)
           })
       }
  });

dbNew.js - My database module file

module.exports = {
    checkUserID: function(userID){
        var isExist;
        return new Promise(function(resolve,reject){
            client.connect(err => {
                const collection = client.db("over_ride").collection("users");                  
               collection.find({user_id:userID}).count().then(function(checkCount){
                    if(checkCount>0){
                        isExist = true;
                    }
                    else{
                        isExist = false;
                    } 
                    resolve(isExist);
                    client.close()

                  })         
             });      
        });
        },
        getAccessToken: function(userID){

            return new Promise(function(resolve,reject){
                client.connect(err => {
                    const collection = client.db("over_ride").collection("users");
                                         collection.findOne({user_id:userID}).then(function(result){
                        console.log(result)
                    })

                    client.close()
                    // resolve(result.social_media.viber.access_token);                
                })
            })

        }

  }
sassy_rog
  • 1,077
  • 12
  • 30
  • I found this question had a correct answer: https://stackoverflow.com/questions/52991359/topology-was-destroyed-when-using-mongodb-with-native-driver-and-express-js/53001171 – Daniel Hallgren Apr 27 '20 at 12:08

1 Answers1

0

You should close the connection after the findOne operation was done:

 collection.findOne({user_id:userID}).then(function(result){
  console.log(result)
  client.close()
})
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151