I was following this post How to Integrate MongoDB Into Your Next.js App by @ado and noticed that if you make a bunch of requests through your Next.js Api Routes in dev mode (eg yarn dev) and then stop dev mode (eg ctrl+c) - you can see in the MongoDB logs that it releases a tonne of connections. Somewhere along the way the connections aren’t closing after each request and are just staying active until you stop Next.js
@ado did you notice anything like this yourself?
PS: I also noticed that your connectToDatabase
function waits for the promise to complete before caching, which means that if you call this rapidly multiple times you will end up with more than one connection. Here is my revisted version:
import { MongoClient } from 'mongodb'
let uri = process.env.MONGO_URI
let dbName = process.env.MONGO_DB
let promise = null
let cached = null
if (!uri) throw new Error('Missing environment variable MONGO_URI')
if (!dbName) throw new Error('Missing environment variable MONGO_DB')
export async function connectToDatabase() {
if (cached) return cached
if (!promise) {
promise = MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
}
const client = await promise
const db = await client.db(dbName)
cached = {
client,
db,
}
return cached
}