1
export const client = new MongoClient(
  process.env.ATLAS_URI,
  // TODO: Figure out what this is and why it's needed to turn off deprecation warning
  {
    useUnifiedTopology: true,
  }
);

Following this guide and all make sense...but she is just doing one 'call' and then close().

I need to keep doing repeated calls:

export const getAllProducts = async () => {
  try {
    await client.connect();
    const cursor = await client.db("products").collection("data").find();
    return await cursor.toArray();
  } catch (err) {
    throw new Error(err);
  } finally {
    await client.close();
  }
};

The first call is fine. After that: Error: MongoError: Topology is closed, please connect

I honestly don't quite understand what Topology means, but evidently it's the close() that's contributing to the issue.

It doesn't make sense that I set up new MongoClient and the ATLAS_URI does have the 'database name' in there...so why I have to connect specify that again?

Anyway, the main part of my ❓ stands: Do I just keep a separate process going and not close it? Do I start back with a whole new MongoClient each time?

CodeFinity
  • 1,142
  • 2
  • 19
  • 19
  • After seeing some discussion [here](https://stackoverflow.com/questions/14495975/why-is-it-recommended-not-to-close-a-mongodb-connection-anywhere-in-node-js-code) I choose to not add the `finally` in that one. – CodeFinity Jun 18 '20 at 03:26

1 Answers1

1

I'll just put a brief answer here incase anyone runs into this.

The Mongodb documentation for the Node.js driver will give you simple examples that include the client.connect()and client.close() methods just to give you a runnable example of making a simple call to the database but in a real server application you are just opening the connection to the client once during start up and typically only closing when the server application is being closed.

So in short: You don't need to open and close and connection everytime you want to perform some action on your database.

Nick Pineda
  • 6,354
  • 11
  • 46
  • 66