Middleware that creates only one connection, that initialized before first request is recieved and shares it for all next incoming requests.
First - install middleware in project:
npm i express-mongo-db mongodb --save
Second - add middleware to express application:
var app = require('express')();
app.use(require('express-mongo-db')(require('mongodb')));
Now you got req.db
object of Mongodb database in every request handler.
Creates middleware with passed mongodb module instance (this is useful for promisification).
You can pass options to constructor of middleware function like this: require('express-mongo-db')(options)
where options
is an object with fields described below.
Also you can modify defaults value in config
property of middleware contructor like this:
var mongodb = require('express-mongo-db');
mongodb.config.readPreference = 'secondary';
var app = require('express')();
app.use(mongodb(require('mongodb')));
app.get('/', function(req, res) {
req.db.find(/* ... */);
});
hosts
- servers or replicas array (default: [{host: '127.0.0.1', port: 27017}])db
- name of database (default:test
)options
- object, that passed toname
- user name for authenticationpwd
- password for authentication- MongoClient.connect.
- And all options from connect-once, such as
reconnectWait
andheartbeat
function.
To know what's up in your life, we provide event-emitter to listen to. For example - this is how you know, that reconnecton happening:
var mongodb = require('express-mongo-db')(require('mongodb'), options);
mongodb.connection.on('reconnect', function(err) {
console.log("Reconnecting to mongo (" + this.retries + " retries left). " + (err.stack ? err.stack : err));
});
Also you can subscribe on connection event:
var mongodb = require('express-mongo-db')(require('mongodb'), options);
mongodb.connection.when('available', function(err, db) {
});
express-mongo-db
will start attempts to connect straight after require.