Skip to content

Connector, that actually retries to connect to mongodb

Notifications You must be signed in to change notification settings

barmaglot92/express-mongo-db

 
 

Repository files navigation

express-mongo-db

NPM version Build Status Coverage Status Dependency Status

Middleware that creates only one connection, that initialized before first request is recieved and shares it for all next incoming requests.

Usage

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.

API

express-mongo-db(mongodb, [options])

Creates middleware with passed mongodb module instance (this is useful for promisification).

Options

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 to
  • name - user name for authentication
  • pwd - password for authentication
  • MongoClient.connect.
  • And all options from connect-once, such as reconnectWait and heartbeat function.

Events

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.

About

Connector, that actually retries to connect to mongodb

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%