How to test Connection Pooling in NodeJS using MongoDB Database?
1 Answers
Instead of having our app wait around for a request before connecting to the database we're going to have it connect when the application starts, and we're going to give ourselves a pool of connections to draw from as and when we need them.
Here we're using the node-mongodb-native driver, which like most available MongoDB drivers has an option that you can use to set the size of your connection pool. For this driver, it's called poolSize
, and has a default value of 5. We can make use of the poolsize
option by creating a database connection variable in advance, and letting the driver allocate available spaces as new connection requests come in:
// This is a global variable we'll use for handing the MongoDB client
var mongodb;
// Connection URL
var url = '[connectionString]';
// Create the db connection
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
mongodb=db;
}
);
To change the size of the connection pool from the default, we can pass poolSize
in as an option:
// Create the database connection
MongoClient.connect(url, {
poolSize: 10
// other options can go here
},function(err, db) {
assert.equal(null, err);
mongodb=db;
}
);
Now we have a connection ready and waiting. To use our new connection, we just need to make use of our new global variable, mongodb
when a request is made:
// Use the connect method to connect to the server when the page is requested
app.get('/', function(request, response) {
mongodb.listCollections({}).toArray(function(err, collections) {
assert.equal(null, err);
collections.forEach(function(collection) {
console.log(collection);
});
})
response.send('See console for a list of available collections');
});

- 1
- 4
- 12