I've been using Mongoose to connect Mongodb with my nextjs application, everything was working fine in the development mode, but when I deployed the project, even a single user (me) is taking around 60 to 80 connections. And when I shared the link with 3/4 of my friends, the connection has reached 500 connections limit.
Here's my initDB file's code:
import mongoose from "mongoose";
const MONGO_URI = process.env.MONGO_URI;
if (!MONGO_URI) {
throw new Error("Error Code: grx30xd33d");
}
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
async function initDB() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true,
};
mongoose.set("strictQuery", false);
cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => {
return mongoose;
});
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.conn;
}
export default initDB;
And this is my page which is using the initDB.
import initDB from "../../../helpers/initDB";
import directorySchema from "../../../models/directory/directorySchema ";
export default async function handler(req, res) {
await initDB();
return new Promise(async (resolve, reject) => {
try {
const userProf = await directorySchema
.find()
.limit(20)
.sort({ _id: -1 })
.then(async (response) => {
if (response !== null) {
res.json({
success: true,
data: response,
message: "Data Fetched Successfully",
});
} else {
return res.json({
success: false,
message: "Invalid data response",
});
}
})
.catch((error) => {
console.log(error);
res.json(error);
res.status(405).end();
return reject();
});
} catch (error) {
console.log(error);
}
});
}
The response is working fine, I'm getting the required response, but the connection limit is reaching in mongodb.
Here's the screenshot of connection while writing this question.