1

I am using using NodeJS and MongoDb as a backend service in my android application.I want to know how can I pool connections so that it minimize the load on server and make fast operations and how to close the connection to database after performing operation.

This is what I have been done so far:

const express = require('express');
const bodyParser = require('body-parser');
const env = require('dotenv').config();
const MongoClient = require('mongodb').MongoClient;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.post('/add', (req,res) => {


  var data = {

    User_id: req.body.userId,
    Email:req.body.email,
    Name: req.body.name,
    Book_name: req.body.bookName,
  };

  MongoClient.connect(dburl, {useNewUrlParser:true} ,(err,client) => {

          if(err){

            console.log("Error".red, +err);
          }
          else{

            var collect = client.db('Mydb').collection('Books');

            collect.insertOne(data, (err,resp) =>{

                  if(err){

                    console.log("Error", +err);
                  }
                  else{

                    console.log("Successfully inserted");
                  }

                  client.close();
            });

        }

     });

 });

  app.listen(port,() => {

       console.log("App is running on:" +port);
  }); 

Someone please let me know what else need to be added in above code to achieve desired results.Any help would be appreciated.

THANKS

1 Answer 1

2

MongoClient by default sets up a connection pool of size 5. You can initiliaze the connection and reuse it.

let connection;
MongoClient.connect(dburl, {useNewUrlParser:true} ,(err,client) => {
  if(err){
    console.log("Error".red, +err);
  }
  connection = client;
  // maybe move your app.listen here to make sure server is started after connection is acquired or something equivalent
})

// elsewhere after connection is established:
connection.db('Mydb').collection('Books');

To increase/decrease the pool size you can pass the poolSize option with the required number.

Sign up to request clarification or add additional context in comments.

2 Comments

where should I use poolSize and what maximum number can we give it to.
where should I use poolSize in your options ex: {useNewUrlParser:true, poolSize: 6} as for maximum number, it's advisable not to allocate beyond your cpus total available thread

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.