Mongoose:Error when send a second request on the server

80 views Asked by At

I'm making an API for my app, the app is in MERN stack, I make a separate Database for every account and its information (every account along with it's info is in a separate DB so each DB for each account)

I have a middleware which runs on every request and decrypts the auth-token retrieves the user's DB name and connects to the DB

It works fine the first time I send a request, but gives this error second time I send a request (the middleware name is connectToDB)

The Error:

MongooseError: Connection was force closed at NativeCollection. [as findOne]

the error is causing at this line

const company = await Company.findById(data.company).select("-password")

my middleware:

const jwt = require('jsonwebtoken');
const JWT_SECRET = "PASSjajghjklnaslg"
const Company = require("../models/Company");
const mongoose = require("mongoose");
const Admin = require('../models/Admin');
const Employee = require('../models/Employee');
const Manager = require('../models/Manager');
const SubAdmin = require('../models/SubAdmin');
const URI = "mongodb://0.0.0.0:27017/";

const connectToDB = async (req, res, next) => {
    const token = req.header("auth-token");

    if (!token) {
        next()
        return
    }
    try {
        const data = jwt.verify(token, JWT_SECRET);
        let Account;

        const dbName = data.companyEmail.replace(/[.]/g, '%2e')

        const adminDb = mongoose.connection.db.admin();
        const result = await adminDb.listDatabases();
        const dbsNames = result.databases.map(db => db.name);

        if (!dbsNames.includes(dbName)) {
            res.status(401).send("Access denied");
            return
        }
        await mongoose.disconnect()
        await mongoose.connect(`${URI}${encodeURIComponent(dbName)}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        })

        if (data.accountType == "company") {
            const company = await Company.findById(data.company).select("-password")
            const anyDoc = await Company.findOne({})

            if (!company && !anyDoc) {
                await mongoose.connection.db.dropDatabase()
                res.status(401).send("Access denied");
                return
            }
            if (!company) {
                res.status(401).send("Access denied");
                return
            }

            res.locals.company = company

            next()
            return
        } else if (
            data.accountType == "admin" ||
            data.accountType == "subAdmin" ||
            data.accountType == "manager" ||
            data.accountType == "employee"
        ) {

            if (req.query.role == "admin") {
                Account = Admin;
                accountType = "admin"
            } else if (req.query.role == "subAdmin") {
                Account = SubAdmin;
                accountType = "subAdmin"
            } else if (req.query.role == "manager") {
                Account = Manager;
                accountType = "manager"
            } else if (req.query.role == "employee") {
                Account = Employee;
                accountType = "employee"
            } else {
                return res.status(400).send("Invalid role")
            }

            const account = await Account.findById(data.user).select("-password")

            if (!account) {
                res.status(401).send("Access denied");
                return
            }

            res.locals.company = account

            next()
            return
        } else {
            return res.status(400).send('bad request')
        }


    }
    catch (err) {

        console.log(err)

        res.status(401).send({
            errors: [
                "Access denied"
            ]
        })

        return
    }
}

module.exports = connectToDB;
0

There are 0 answers