Last active
March 28, 2023 18:38
-
-
Save adityaparmar03/3039afbf1403abd00e26b6715ad6cf41 to your computer and use it in GitHub Desktop.
This is a code for connection pooling in mongoDB in NodeJS. In below code, MongoJS file establish connection and appJS file call MongoJS file for establishing connection. Then, Other routes use this same connection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Mongo.js*/ | |
| var MongoClient = require('mongodb').MongoClient; | |
| var url = "mongodb://localhost:27017/yourdatabasename"; | |
| var assert = require('assert'); | |
| var connection=[]; | |
| // Create the database connection | |
| establishConnection = function(callback){ | |
| MongoClient.connect(url, { poolSize: 10 },function(err, db) { | |
| assert.equal(null, err); | |
| connection = db | |
| if(typeof callback === 'function' && callback) | |
| callback(connection) | |
| } | |
| ) | |
| } | |
| function getconnection(){ | |
| return connection | |
| } | |
| module.exports = { | |
| establishConnection:establishConnection, | |
| getconnection:getconnection | |
| } | |
| /*app.js*/ | |
| // establish one connection with all other routes will use. | |
| var db = require('./routes/mongo') | |
| db.establishConnection(); | |
| //you can also call with callback if you wanna create any collection at starting | |
| /* | |
| db.establishConnection(function(conn){ | |
| conn.createCollection("collectionName", function(err, res) { | |
| if (err) throw err; | |
| console.log("Collection created!"); | |
| }); | |
| }; | |
| */ | |
| // anyother route.js | |
| var db = require('./mongo') | |
| router.get('/', function(req, res, next) { | |
| var connection = db.getconnection() | |
| res.send("Hello"); | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment