peeter-tomberg / hapi-mongodb-promises

A simple Hapi MongoDB connection plugin with baked in promises.
2 stars 0 forks source link

Hapi-MongoDB-promises


Codeship Status for peeter-tomberg/hapi-mongodb-promises Coverage Status Code Climate

This is a mongo db connection plugin and a promise wrapper for the mongo API. It enables your Hapi application to connect to mongodb and run queries.

It takes 2 options :

Several functions are exposed by this plugin :

This plugin also exposes some objects :


Install:

    npm install hapi-mongodb-promises --save

Usage example :

var Hapi = require("hapi");

var dbOpts = {
    "url": "mongodb://localhost:27017/test"
};

var server = new Hapi.Server(8080);

server.pack.register({
    plugin: require('hapi-mongodb-promises'),
    options: dbOpts
}, function (err) {
    if (err) {
        console.error(err);
        throw err;
    }
});

server.route( {
    "method"  : "GET",
    "path"    : "/users/{id}",
    "handler" : usersHandler
});

function usersHandler(request, reply) {
    var mongo = request.server.plugins['hapi-mongodb-promises'];
    mongo
        .findOneById('users', request.params.id)
        .then(reply)
        .otherwise(function (err) {
            reply(Hapi.error.internal('Internal MongoDB error', err));
        });
};

server.start(function() {
    console.log("Server started at " + server.info.uri);
});