Skip to content

Instantly share code, notes, and snippets.

@LearnWebCode
Created August 28, 2024 18:11
Show Gist options
  • Save LearnWebCode/9b412da25787489e82141717d3995d1f to your computer and use it in GitHub Desktop.
Save LearnWebCode/9b412da25787489e82141717d3995d1f to your computer and use it in GitHub Desktop.
MongoDB integration with Next.js 14
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