Why cache MongoDB connection in Next.js? And does it work?

Viewed 168

I'm creating a Next.js application and I noticed that many developers cache the MongoDB connection. For example

let cachedClient = null;
let cachedDb = null;

export async function connectToDatabase() {
    if (cachedClient && cachedDb) {
        return {
            client: cachedClient,
            db: cachedDb,
        };
    }

    const opts = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    };

    let client = new MongoClient(MONGODB_URI, opts);
    await client.connect();
    let db = client.db(MONGODB_DB);

    cachedClient = client;
    cachedDb = db;

    return {
        client: cachedClient,
        db: cachedDb,
    };
}

or

let cached = global.mongoose

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect () {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      bufferCommands: false,
      bufferMaxEntries: 0,
      useFindAndModify: true,
      useCreateIndex: true
    }

    cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => {
      return mongoose
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

I've never seen that in Express apllications so I have 2 questions:

  1. Why is caching database connection such a common thing in Next.js while I've never seen that in Express.js. What's he reason for that? How does it work? And is it worth it?
  2. As you can see in the examples above some developer use useual let-variables while some other developer use global variables. What's the difference and which is the better solution?
1 Answers

In Next.Js you can cache some variables and mongo connection is one of them. It will significantly improve the response time of your application because the first call to your page will make all calls to mongo to estabilish a connection and it can take more than 2 seconds just to do this, after you have this connection stabilished you can reuse in future calls to that same page (in cases of local cache) and it'll dispense those 2 seconds spent on creating connection (resulting in a WAY faster response to your user).

eg:

1° Request to your page:
2300ms spent to get a response //Had to establish a new connection with mongo

2° Request to your page:
230ms spent to get a response //Used cached connection

3° Request to your page:
180ms spent to get a response //Used cached connection

4° Request to your page:
210ms spent to get a response //Used cached connection
...

The difference between the global cache and "let" cache is which functions will use the same connection. Depending in what your application does you can use global cache and it will prevent from every function in your app create your own connection with mongo and spent that 2 seconds I've mentioned.

Related