1

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

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
vfbraton
  • 83
  • 1
  • 6

3 Answers3

5

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 :-)

MikeAinOz
  • 126
  • 1
  • 10
  • 24
  • 1
    Just gonna add more references here: https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connection-pooling https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application – Koodies Sep 14 '20 at 02:00
  • Considering this example and that I have as a definition NOT to be able to use something more complete like mongoose, I saw that we can use the database variable inside the route with express (famous locals.db), but I don't think that would be interesting for an architecture based in DDD. In this case, do you have any recommendations that solve this problem? – vfbraton Sep 19 '20 at 13:27
2

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.

ecoplaneteer
  • 1,918
  • 1
  • 8
  • 29
ZaO Lover
  • 433
  • 2
  • 13
  • Thanks for that but i know mongoose , my question is not about specific Node.js or mongoDB i just this a simple example – vfbraton Sep 19 '20 at 13:02
  • Yeah, I know. Well, in my opinion, you should not close the connection to database until the app is exited. Well, if you want to use multiple database, I think it is good to closing the connection when you are going to connect a new one. – ZaO Lover Sep 19 '20 at 13:48
  • There is no need to close the previous connections while trying to use other connections. https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project – ecoplaneteer Oct 08 '20 at 03:26
1

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.

nixxo_raa
  • 391
  • 8
  • 21
  • An interesting point, but thinking about applications focused on cpu bounding, what would be the most appropriate way to work with this concept? For example in golang we can use context but in other situations like rust or node it is not interesting to use global variables – vfbraton Sep 19 '20 at 13:23