diff --git a/examples/with-mongodb/util/mongodb.js b/examples/with-mongodb/util/mongodb.js index f5a50bcfeebe681..6a376d197e67488 100644 --- a/examples/with-mongodb/util/mongodb.js +++ b/examples/with-mongodb/util/mongodb.js @@ -3,9 +3,6 @@ import { MongoClient } from 'mongodb' let uri = process.env.MONGODB_URI let dbName = process.env.MONGODB_DB -let cachedClient = null -let cachedDb = null - if (!uri) { throw new Error( 'Please define the MONGODB_URI environment variable inside .env.local' @@ -18,20 +15,24 @@ if (!dbName) { ) } +// global is used here to ensure the connection is cached across +// hot-reloads during development. +let cached = global.mongo +if (!cached) cached = global.mongo = {} + export async function connectToDatabase() { - if (cachedClient && cachedDb) { - return { client: cachedClient, db: cachedDb } + if (cached.connection) return cached.connection + if (!cached.promise) { + cached.promise = new Promise(async (resolve) => { + const client = await MongoClient.connect(uri, { + useNewUrlParser: true, + useUnifiedTopology: true, + }) + const db = await client.db(dbName) + cached.connection = { client, db } + resolve() + }) } - - const client = await MongoClient.connect(uri, { - useNewUrlParser: true, - useUnifiedTopology: true, - }) - - const db = await client.db(dbName) - - cachedClient = client - cachedDb = db - - return { client, db } + await cached.promise + return cached.connection }