A simple Hapi MongoDB connection plugin, accessing one or several connections pools through server or request properties
JavaScript
Clone or download
Latest commit 9ff0a06 Jun 12, 2018
Permalink
Failed to load latest commit information.
lib Cleanup for #35. Nov 11, 2017
test Upgrade for hapi v17. Fixes #33. Nov 6, 2017
.gitignore Upgrade for hapi v17. Fixes #33. Nov 6, 2017
.npmignore Add npmignore Feb 22, 2017
.nvmrc Upgrade for hapi v17. Fixes #33. Nov 6, 2017
.travis.yml Upgrade for hapi v17. Fixes #33. Nov 6, 2017
LICENSE Update LICENSE Dec 9, 2014
README.md Fix link. Fixes #39. Jun 12, 2018
package.json 7.1.0 Nov 11, 2017

README.md

npm version Build Status Dependencies Status DevDependencies Status

Hapi-MongoDB

This is a plugin to share a common MongoDB connection pool across the whole Hapi server.

Options can be a single object with the following keys or an array of the same kind if you need multiple connections :

  • url: Optional. MongoDB connection string (eg. mongodb://user:pass@localhost:27017).
    • defaults to mongodb://localhost:27017
  • settings: Optional. Provide extra settings to the connection, see documentation.
  • decorate: Optional. Rather have exposed objects accessible through server and request decorations. You cannot mix different types of decorations.
    • If true, server.mongo or request.mongo
    • If it's a string, server.<string> or request.<string>

Several objects are exposed by this plugin :

  • db : connection object to the database, if an array was provided for the configuration, it will be an array of connections in the same order
  • lib : mongodb library in case you need to use it
  • ObjectID : mongodb ObjectID constructor in case you need to use it

Usage example :

const Hapi = require('hapi');
const Boom = require('boom');

const launchServer = async function() {
    
    const dbOpts = {
        url: 'mongodb://localhost:27017/test',
        settings: {
            poolSize: 10
        },
        decorate: true
    };
    
    const server = Hapi.server();
    
    await server.register({
        plugin: require('hapi-mongodb'),
        options: dbOpts
    });

   server.route( {
        method: 'GET',
        path: '/users/{id}',
        async handler(request) {

            const db = request.mongo.db;
            const ObjectID = request.mongo.ObjectID;

            try {
                const result = await db.collection('users').findOne({  _id: new ObjectID(request.params.id) });
                return result;
            }
            catch (err) {
                throw Boom.internal('Internal MongoDB error', err);
            }
        }
    });

    await server.start();
    console.log(`Server started at ${server.info.uri}`);
};

launchServer().catch((err) => {
    console.error(err);
    process.exit(1);
});

Compatibility level

  • Hapi >= 17
  • Node.js >= 8

Ships with mongodb >= 2.