Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
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'
);
}

if (!dbName) {
throw new Error(
'Please define the MONGODB_DB environment variable inside .env.local'
);
}

export async function connectToDatabase() {
if (cachedClient && cachedDb) {
return { client: cachedClient, db: cachedDb };
}

const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const db = await client.db(dbName);

cachedClient = client;
cachedDb = db;

return { client, db };
}
Loading