Reputation: 3271
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
Upvotes: 1
Views: 119
Reputation: 6718
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.
Upvotes: 2