Created
January 9, 2025 11:40
-
-
Save paulweezydesign/fe268b21f81230a9c5c5c27c969f8672 to your computer and use it in GitHub Desktop.
connect to mongodb with mongoose-nextjs
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, { connect } from "mongoose"; | |
declare global { | |
var mongoose: { | |
promise: ReturnType<typeof connect> | null; | |
conn: typeof _mongoose | null; | |
}; | |
} | |
const MONGODB_URI = process.env.MONGODB_URI; | |
if (!MONGODB_URI || MONGODB_URI.length === 0) { | |
throw new Error("Please add your MongoDB URI to .env.local"); | |
} | |
/** | |
* Global is used here to maintain a cached connection across hot reloads | |
* in development. This prevents connections from growing exponentially | |
* during API Route usage. | |
*/ | |
let cached = global.mongoose; | |
if (!cached) { | |
cached = global.mongoose = { conn: null, promise: null }; | |
} | |
async function connectDB() { | |
if (cached.conn) { | |
console.log("🚀 Using cached connection"); | |
return cached.conn; | |
} | |
if (!cached.promise) { | |
const opts = { | |
bufferCommands: false, | |
}; | |
cached.promise = connect(MONGODB_URI!, opts) | |
.then((mongoose) => { | |
console.log("✅ New connection established"); | |
return mongoose; | |
}) | |
.catch((error) => { | |
console.error("❌ Connection to database failed"); | |
throw error; | |
}); | |
} | |
try { | |
cached.conn = await cached.promise; | |
} catch (e) { | |
cached.promise = null; | |
throw e; | |
} | |
return cached.conn; | |
} | |
export default connectDB; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment