Access an object encapsulated in a separate function

Access an object encapsulated in a separate function
0.0 0

#1

I’m not sure how to access objects inside a function from another function. Here’s an example of 2 functions, one that opens and one that closes a db connection.

const connect_to_database = () => {
    const db_connection = MongoClient.connect(database_url, (error, client) => {
            const db = client.db('collection');
}); 
    return db_connection; 
};

const close_connection = (connection_function) => {
    // todo access the object that has the close function. Then execute it 
};

// close_connection(connect_to_database) ??? Fix the logic

Running close_connection(client) was simple when they were encapsulated in the same function. But I am confused on how to access it from the outside, since the client object is represented as a local variable. You can see above that I’m trying to return the encapsulating function so that I can access it from the outside. I doubt this is the right train of thought though.


#2

Here is the original code sample (Mongo docs are a bit old so I had to modify it based on SO posts saying you need to refer to a client object now instead of the db object directly)

MongoClient.connect(url, (err, client) => {
  	const db = client.db('test-collection')
  console.log("Connected successfully to server");

  db.close();
});