Skip to content
Merged
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
40 changes: 32 additions & 8 deletions lib/database.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,38 @@
import mongoose from 'mongoose';

const MONGODB_URI = process.env.MONGODB_URI;

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

/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongoose;

if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}

export default async function dbConnect() {
// check if we have a connection to the database or if it's currently
// connecting or disconnecting (readyState 1, 2 and 3)
if (mongoose.connection.readyState >= 1) {
return;
if (cached.conn) {
return cached.conn;
}

return mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
if (!cached.promise) {
const opts = {
bufferCommands: false
};

cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
return mongoose;
});
}

cached.conn = await cached.promise;

return cached.conn;
}