Skip to content

Commit d77d08b

Browse files
mongo db multiple connections fix
1 parent 10ca176 commit d77d08b

File tree

1 file changed

+31
-17
lines changed

1 file changed

+31
-17
lines changed

src/lib/mongoose.ts

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,41 @@
11
import mongoose from "mongoose";
2-
3-
if (!process.env.MONGODB_URI) {
4-
throw new Error("Please add your Mongo URI to .env.local");
2+
declare global {
3+
// eslint-disable-next-line no-var
4+
var mongoose: { conn: mongoose.Mongoose | null; promise: Promise<mongoose.Mongoose> | null } | undefined; // This must be a `var` and not a `let / const`
55
}
66

7-
const uri = process.env.MONGODB_URI;
7+
let cached = global.mongoose;
88

9-
let isConnected = false;
9+
cached ??= global.mongoose = { conn: null, promise: null };
1010

11-
export const connectToDatabase = async () => {
12-
if (isConnected) {
13-
return;
14-
}
11+
export async function connectToDatabase() {
12+
const MONGODB_URI = process.env.MONGODB_URI!;
1513

16-
if (mongoose.connection.readyState === mongoose.ConnectionStates.connected) {
17-
isConnected = true;
18-
return;
14+
if (!MONGODB_URI) {
15+
throw new Error(
16+
"Please define the MONGODB_URI environment variable inside .env.local",
17+
);
1918
}
2019

20+
if (cached?.conn) {
21+
return cached.conn;
22+
}
23+
if (cached && !cached.promise) {
24+
const opts = {
25+
bufferCommands: false,
26+
};
27+
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
28+
return mongoose;
29+
});
30+
}
2131
try {
22-
await mongoose.connect(uri);
23-
isConnected = true;
24-
} catch (error) {
25-
throw new Error("Failed to connect to MongoDB");
32+
cached!.conn = await cached!.promise;
33+
} catch (e) {
34+
if (cached) {
35+
cached.promise = null;
36+
}
37+
throw e;
2638
}
27-
};
39+
40+
return cached?.conn;
41+
}

0 commit comments

Comments
 (0)