'MongoDB & Next.js – two connections at the same time = Error: Cannot use a session that has ended

I'm creating an application in Next.js and I'm at a stage where I need to load data from two different API endpoints that connect to MongoDB.

Specifically:
I have an index.js file that contains two components.

  1. DashMenu.js (Component that displays basic information)
  2. LunchMenuEditor.js (Component in which there is a textarea and the text of the lunch menu changes)

The problem occurs when I need to retrieve data from the address .../api/specials in the DashMenu component using useEffect() and at the same time the LunchMenuEditor component is loaded, which needs to retrieve data from the address .../api/[week].js?year=2022. The result is an error: "MongoExpiredSessionError: Cannot use a session that has ended".

In my opinion there is an error in db.connect() and disconnect() in api files (see code). If I delete db.disconnect(), everything works, but the connection remains open.

I also tried db.connect() to insert it in setTimeout() with a wait of 3 seconds, it worked, but it occurs to me that it is not professional and I would be concerned about long-term sustainability.

So my questions are:

  1. How to solve the problem "MongoExpiredSessionError: Cannot use a session that has ended"
  2. Will it matter if the connection to MongoDB remains open? Does the connection end automatically after some time?

Thank you for every answer 🙂


Codes:

.../api/[week]:

import db from "../../../utils/db";
import LunchMenu from "../../../models/LunchMenu";

export default async (req, res) => {

  await db.connect();
  if (req.method === "GET") {
    const lunchMenu = await LunchMenu.find({ week: 4, year: 2022 });
    res.json(lunchMenu);
  }
  await db.disconnect();
};

.../api/specials:

import db from "../../../utils/db";
import Specials from "../../../models/Specials";

export default async (req, res) => {
  await db.connect();
  const specials = await Specials.find({ visible: true });
  await db.disconnect();
  res.json(specials);
};

utils/db.js

import mongoose from "mongoose";

const connection = {};

async function connect() {
  if (connection.isConnected) {
    console.log("Already connected.");
    return;
  }

  if (mongoose.connection.length > 0) {
    connection.isConnected = mongoose.connections[0].readyState;
    if (connection.isConnected === 1) {
      console.log("Uses previous connections.");
      return;
    }
    await mongoose.disconnect();
  }

  const db = await mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
  console.log("A new connection has been established.");
  connection.isConnected = db.connections[0].readyState;
}

async function disconnect() {
  if (connection.isConnected) {
    await mongoose.disconnect();
    connection.isConnected = false;
    console.log("Disconnected.");
  }
}

const db = { connect, disconnect };
export default db;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source