diff --git a/examples/with-mongodb/util/mongodb.js b/examples/with-mongodb/util/mongodb.js index 4f0371eddde6a..461aa39959685 100644 --- a/examples/with-mongodb/util/mongodb.js +++ b/examples/with-mongodb/util/mongodb.js @@ -20,26 +20,23 @@ if (!MONGODB_DB) { * during API Route usage. */ let cached = global.mongo -if (!cached) cached = global.mongo = {} +if (!cached) cached = global.mongo = { conn: null, promise: null } export async function connectToDatabase() { if (cached.conn) return cached.conn if (!cached.promise) { - const conn = {} const opts = { useNewUrlParser: true, useUnifiedTopology: true, } cached.promise = MongoClient.connect(MONGODB_URI, opts) .then((client) => { - conn.client = client - return client.db(MONGODB_DB) - }) - .then((db) => { - conn.db = db - cached.conn = conn + return { + client, + db: client.db(MONGODB_DB), + } }) } - await cached.promise + cached.conn = await cached.promise return cached.conn }