zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time 😉.

Made with by Zahid
views
zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time 😉.
Made with by Zahid
views
Make sure you’ve installed mongodb and mongoose :
1npm install mongodb mongoose
Add the following environment variables to your .env file:
1MONGODB_URI=
2MONGODB_DBNAME=
Now, pop this into your project to handle MongoDB connection efficiently. Below is an example that uses caching to avoid multiple connections during hot reloads (especially useful in Next.js):
1import mongoose, { Mongoose } from "mongoose";
2
3const MONGODB_URL = process.env.MONGODB_URI!;
4const MONGODB_DBNAME = process.env.MONGODB_DBNAME!;
5
6interface MongooseConn {
7 conn: Mongoose | null;
8 promise: Promise<Mongoose> | null;
9}
10
11let cached: MongooseConn = (global as any).mongoose;
12
13if (!cached) {
14 cached = (global as any).mongoose = {
15 conn: null,
16 promise: null,
17 };
18}
19
20export const connect = async () => {
21 if (cached.conn) return cached.conn;
22
23 cached.promise =
24 cached.promise ||
25 mongoose.connect(MONGODB_URL, {
26 dbName: MONGODB_DBNAME,
27 bufferCommands: false,
28 connectTimeoutMS: 30000,
29 });
30
31 cached.conn = await cached.promise;
32
33 return cached.conn;
34};
This setup ensures a stable MongoDB connection in both development and production environments. Clean, simple, and efficient.
Tech Stack: Next.js, ShadCN UI, Clerk.js