vfbraton
vfbraton

Reputation: 93

Should I open/close database connection after every query/insert?

Hey everyone i'm developer a simple app in last days using nodejs and create this function to return client instance from mongodb

const mongodb = require("mongodb");
const { db } = require("../config/env");

const conection = async () => {
    try {
        const client = await mongodb.MongoClient.connect(db.uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        return client;
    } catch (error) {
        throw error;
    }
};

module.exports = conection;

and i make this simple function for acess data layer and return records instered

const index = async ({ limit = 10, offset = 0, filter = {} }) => {
    const client = await conection();
    if (filter._id) {
        filter._id = mongodb.ObjectID(filter._id);
    }
    try {
        const collection = client.db("api").collection("user");
        const data = await collection
            .find({ ...filter })
            .skip(offset)
            .limit(limit)
            .toArray();
        return data;
    } catch (error) {
        throw new Error(error);
    } finally {
        await client.close();
    }
};

I would like to know if I really need to make the connection and close it with each query or should I keep the connection open

NOTE: in this case I am using a simple Atlas cluster (free) but I would like to know if I should do this also when working with sql banks like postgres

Upvotes: 1

Views: 3824

Answers (3)

ZaO Lover
ZaO Lover

Reputation: 433

You can use the mongoose module for managing MongoDB.

  • Installation

    npm install mongoose

  • Usage

    mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
    

I am sure that Mongoose can help you solve your issues.

Upvotes: 2

nixxo_raa
nixxo_raa

Reputation: 402

It's a good practice to do so. so that after every operation(insert etc) you close the connection and before every operation(insert etc) you reopen the connection.

Upvotes: 1

MikeAinOz
MikeAinOz

Reputation: 128

Don't close your connection unless you are exiting your app, and then make sure you do. Ensure that you are using the same connection when you come back to do more I/O. Database connections are resource-intensive and should be established as few times as possible and shared as much as possible. You can also get middleware problems with connections like ODBC if you don't pick up existing connections and get weird errors like connection pools running out. Get to know your connector and how to use it most effectively, it will be a rewarding activity :-)

Upvotes: 5

Related Questions