'client doesn't close that causes connection error `Topology is closed`

I use following code to connect to mongodb

conn.js

'use strict'
const { MongoClient } = require('mongodb');
const dbconfig = require('../config/index');
const client = new MongoClient(dbconfig.product.dbUrl, { useNewUrlParser: true });
client.connect(function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('mongodb connected');
    }
});
const db = client.db(dbconfig.product.dbName);
module.exports = db;

user.js

const db = require("./conn");
let user = await db.collection("user").find({}).toArray();

I meet an issue that sometimes I will get an error Topology is closed, how can I close the db connection in this case? Thank you.



Sources

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

Source: Stack Overflow

Solution Source