Created
February 10, 2021 11:48
-
-
Save michaltakac/b282fff26105826dee4cabb487070058 to your computer and use it in GitHub Desktop.
MongoDB connection through mongoose in a Next.js app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from "mongoose"; | |
if (!process.env.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.mongo; | |
if (!cached) { | |
cached = global.mongo = { conn: null, promise: null }; | |
} | |
export async function connectToDatabase() { | |
if (cached.conn) { | |
return cached.conn; | |
} | |
if (!cached.promise) { | |
if (mongoose.connection.readyState >= 1) { | |
return; | |
} | |
const opts = { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
useFindAndModify: false, | |
useCreateIndex: true, | |
}; | |
cached.promise = mongoose.connect(process.env.MONGODB_URI, opts); | |
} | |
cached.conn = await cached.promise; | |
console.log(cached) | |
return cached.conn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment