skip to Main Content

I used to connect to the mongodb like this.

import mongoose from "mongoose"

const connectDb = async () => {
    return  mongoose.connect(process.env.MONGO_URI, (err) => {
        if (err) {
          console.log(err);
        } else {
          console.log("connected to mongoDB successfully");
        }
      });

}

export default connectDb

but this creates a new connection on each request. then I learned about cached connection but I don’t know what is the right way to do it using mongoose. I found one video on mongodb’s official yt channel that was creating a cached connection but they did not use mongoose to do that.

I found one method but I am not sure wheather it is a correct way or not but for now it is working fine.

import mongoose from 'mongoose'

const MONGODB_URI = process.env.MONGO_URI

// If MongoDb uri is not provided we will throw an error
if (!MONGODB_URI) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  )
}


// When we first connect to the db we will cache that connection in a variable named cached so that we don't have to connect to the database again and again on each and every request. 
let cached = global.mongoose
// If we don't have cached connection then first we will set conn: null, promise: null
if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

// creating an async function to connect to the db
async function connectDb() {
  // If we have cached connection then we don't  have to make connection once again. we will return the old connection.
  if (cached.conn) {
    return cached.conn
  }

  // If we don't have cached connection then we will create one and return it.

  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    }

    cached.promise = await mongoose.connect(MONGODB_URI, {useNewUrlParser: true}).then((mongoose) => {
      return mongoose
    })
  }

  try {
    cached.conn = await cached.promise
  } catch (e) {
    cached.promise = null
    throw e
  }

  return cached.conn
}

export default connectDb

2

Answers


  1. You can Cache the DB connection

    const url = require('url')
    const MongoClient = require('mongodb').MongoClient
    
    let cachedDb = null // Create cached connection variable
    
    async function connectToDatabase(uri) {
      if (cachedDb) {
        return cachedDb // Prefer cached connection
      }
       // if not cached 
      const client = await MongoClient.connect(uri, { useNewUrlParser: true })
      const db = await client.db(url.parse(uri).pathname.substr(1))
      cachedDb = db // Cache the database connection
      return db
    }
    
    module.exports = async (req, res) => {
      const db = await connectToDatabase(process.env.MONGODB_URI) //calling cached function.
      const collection = await db.collection('users')
      const users = await collection.find({}).toArray()
      res.status(200).json({ users })
    }
    

    As shown above if one’s a connection is established we can store it in cacheDB variable and you can call cached connection whenever required after that.

    ref from :- https://github.com/orgs/vercel/discussions/424 ;

    Login or Signup to reply.
  2. Mongoose have this built-in, and it’s called connection pool. Default is 100 connections, which means Mongoose will open 100 connections to MongoDB server, and it will keep them for all the queries in your server.

    You can override the default to some other number.

    mongoose.createConnection(uri, { maxPoolSize: 10 });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search