DEV Community

Jalish Chauhan
Jalish Chauhan

Posted on

Issue with Mongoose Database Switching Middleware in Express.js

I'm implementing an Express.js middleware to switch between different MongoDB databases using Mongoose based on the request URL. The middleware is supposed to disconnect from the current database and connect to a new one depending on the URL path. However, I'm facing some issues with the implementation, and I would appreciate some guidance.

Here's the middleware code:

const switcher = async (req, res, next) => {
try {
const [, second] = req.url.split("/");
const connection = second === "auth" ? process.env.AUTH_DB_URL : process.env.STORAGE_DB_URL;

if (mongoose.connection.readyState !== 0 && mongoose.connection.client.s.url !== connection) {
  await mongoose.disconnect();
  await mongoose.connect(connection, { keepAliveInitialDelay: true });
  console.log("Connected to", connection);
}

next();
Enter fullscreen mode Exit fullscreen mode

} catch (err) {
console.error(err);
return res.status(500).send({ status: 500, message: "Internal Server Error" });
}
};

What I Expected:
Seamless Switching: I expected the middleware to seamlessly disconnect from the current database and connect to the new one based on the request URL.
Correct Database Operations: After switching, subsequent database operations should be performed on the newly connected database.
No Interruption: The middleware should handle concurrent requests efficiently without causing interruptions or errors.

Top comments (0)