Unverified Commit 82041542 authored by Ash Connell's avatar Ash Connell Committed by GitHub

Fix with-mongodb hot-reload issue and race condition (#17666)

This PR fixes 2 issues with the mongodb example:

### 1. Fallable Caching Strategy

Calling `connectToDatabase()` multiple times before it's cached results in multiple connections being created. The latest one created was becoming the "cached" one and the others dissappear into the background.

This is now fixed by using **promise sharing** so that only one connection can ever be created.

### 2. Problematic Hot Reload

During development you can monitor your database connections and see that it continues to create more and more connections over time. Some users have reported their [databases reaching maximum connection limits](https://github.com/vercel/next.js/discussions/12229).

This is resolved by using `global` to store the cached connection. It's not ideal but it is necessary.
parent f01deeed
import { MongoClient } from 'mongodb' import { MongoClient } from 'mongodb'
let uri = process.env.MONGODB_URI const { MONGODB_URI, MONGODB_DB } = process.env
let dbName = process.env.MONGODB_DB
let cachedClient = null if (!MONGODB_URI) {
let cachedDb = null
if (!uri) {
throw new Error( throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local' 'Please define the MONGODB_URI environment variable inside .env.local'
) )
} }
if (!dbName) { if (!MONGODB_DB) {
throw new Error( throw new Error(
'Please define the MONGODB_DB environment variable inside .env.local' 'Please define the MONGODB_DB environment variable inside .env.local'
) )
} }
export async function connectToDatabase() { /**
if (cachedClient && cachedDb) { * Global is used here to maintain a cached connection across hot reloads
return { client: cachedClient, db: cachedDb } * in development. This prevents connections growing exponentiatlly
} * during API Route usage.
*/
let cached = global.mongo
if (!cached) cached = global.mongo = {}
const client = await MongoClient.connect(uri, { export async function connectToDatabase() {
if (cached.conn) return cached.conn
if (!cached.promise) {
const conn = {}
const opts = {
useNewUrlParser: true, useNewUrlParser: true,
useUnifiedTopology: true, useUnifiedTopology: true,
}
cached.promise = MongoClient.connect(MONGODB_URI, opts)
.then((client) => {
conn.client = client
return client.db(MONGODB_DB)
}) })
.then((db) => {
const db = await client.db(dbName) conn.db = db
cached.conn = conn
cachedClient = client })
cachedDb = db }
await cached.promise
return { client, db } return cached.conn
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment