Created
August 28, 2024 18:11
-
-
Save LearnWebCode/9b412da25787489e82141717d3995d1f to your computer and use it in GitHub Desktop.
MongoDB integration with Next.js 14
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 { MongoClient } from "mongodb" | |
let client | |
let clientPromise | |
if (!process.env.CONNECTIONSTRING) { | |
throw new Error("Please add your MongoDB URI to the .env file") | |
} | |
const uri = process.env.CONNECTIONSTRING | |
const options = {} | |
if (process.env.NODE_ENV === "development") { | |
// In development mode, use a global variable so that the MongoClient instance is not recreated. | |
if (!global._mongoClientPromise) { | |
client = new MongoClient(uri, options) | |
global._mongoClientPromise = client.connect() | |
} | |
clientPromise = global._mongoClientPromise | |
} else { | |
// In production mode, it's best to not use a global variable. | |
client = new MongoClient(uri, options) | |
clientPromise = client.connect() | |
} | |
async function getDatabase() { | |
const client = await clientPromise | |
return client.db() | |
} | |
export async function getCollection(collectionName) { | |
const db = await getDatabase() | |
return db.collection(collectionName) | |
} | |
export default getDatabase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment