Premjith
Premjith

Reputation: 163

set mongodb node.js connection once for all routes using mongoclient

I'm new in node.js and mongo db and i have done my code like this in all my routes.

var express       = require('express');
var router        = express.Router();
var mongo         = require('mongodb');
var MongoClient   = mongo.MongoClient;
var ObjectID      = mongo.ObjectID;
var collection;

//Connection to mongo db using mongo client
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {

    //connection error or success message
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
        throw err;
    } else {
        console.log("connected to the mongoDB");
    }

    //index
    router.get('/', function(req, res) {
        collection = db.collection('category');
        collection.find({}).toArray(function(err, category) {
            collection = db.collection('subcategory');
            collection.find({}).toArray(function(err, subcategory) {
                collection = db.collection('product');
                collection.find({}).toArray(function(err, product) {
                    collection = db.collection('banner');
                    collection.find({status: 'A'}).toArray(function(err, banner) {
                        console.log(banner);
                        res.render('home', 
                            {
                                title           : 'Home', 
                                categorys       : category,
                                subcategorys    : subcategory,
                                products        : product,
                                banner          : banner 
                            }
                        );
                    });
                });
            });
        });
    });
});
module.exports = router; 

please help me to make a connection in common and access it from all my routes without repeating the connection call. thanks in advance

Upvotes: 1

Views: 2926

Answers (2)

Unnikrishnan M R
Unnikrishnan M R

Reputation: 224

You can use Mongoose to connect to MongoDB. With Mongoose you need to connect to the database only once to access it from all the routes. In you app.js add these lines:

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test_db', { useNewUrlParser: true }, function (err) {
  if (err) throw err;
});

and in your routes you can now access MongoDB without having to write any connection code.

Upvotes: 0

notionquest
notionquest

Reputation: 39226

Here is the draft code to keep the connection outside each request (i.e. connect once) and reuses the database/collection variable.

NodeJS Mongo Driver default connection pool size is 5.

Important: db and categoryCollection variables are kept outside each requests.

var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MONGODB_URI = 'mongodb://127.0.0.1:27017/mydb';
var db;
var categoryCollection;
// Initialize connection once
mongodb.MongoClient.connect(MONGODB_URI, function(err, database) {
  if(err) throw err;

  db = database;
  categoryCollection = db.collection('category');
  app.listen(3000);
  console.log('Listening on port 3000');
});
app.get('/', function(req, res) { 
 categoryCollection.find({}).toArray(function(err, category) {  
 });                        
});

Upvotes: 1

Related Questions