1

I have the following method to connect to MongoDB:

import { Db, MongoClient } from 'mongodb';

let cachedConnection: { client: MongoClient; db: Db } | null = null;

export async function connectToDatabase(mongoUri?: string, database?: string) {
  if (!mongoUri) {
    throw new Error(
      'Please define the MONGO_URI environment variable inside .env.local'
    );
  }

  if (!database) {
    throw new Error(
      'Please define the DATABASE environment variable inside .env.local'
    );
  }

  if (cachedConnection) return cachedConnection;

  cachedConnection = await MongoClient.connect(mongoUri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).then((client) => ({
    client,
    db: client.db(database),
  }));

  return cachedConnection!;
}

And I use it in the following way:

const { db, client } = await connectToDatabase(
  config.URI,
  config.USERS_DATABASE
);

const user = await db
  .collection(config.USERS_COLLECTION)
  .findOne({ _id: new ObjectId(userId) });

It seems to be ok, but it is not. The problem of this method is that it doesn't close the connections. For example I have a cluster on Atlas, and the connections keep growing till 500. after that it doesn't serve anymore, goes in timeout and then my backend crashes.

To solve this I tried with client.close() just before returning the response to frontend.

It throws me one error saying MongoError: Topology is closed, please connect. I believe that it closes the connection before it finishes? is it right? Even if I put it after the DB responded.

this is the screenshot of the error:

enter image description here

Do you think there is a way to solve this or I just have to do the entire procedure in each file I need to connect to mongo? Do you also think I did something wrong?

Loudrous
  • 1,039
  • 10
  • 29
  • first of all try to split the code (where `const user`) with await (new style coding), then you can debug it line by line. And whole your question looks like copy of this one https://stackoverflow.com/questions/59942238/mongoerror-topology-is-closed-please-connect-despite-established-database-conn – chavy Mar 31 '22 at 08:51

0 Answers0