Package Exports
- hapi-mongodb
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (hapi-mongodb) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Hapi-MongoDB
This is a plugin to share a common MongoDB connection pool across the whole Hapi server.
It takes 2 options :
- url: MongoDB connection string (eg.
mongodb://user:pass@localhost:27017
), - settings: Optional. Provide extra settings to the connection, see documentation.
Several objects are exposed by this plugin :
db
: connection object to the databaselib
: mongodb library in case you need to use itObjectID
: mongodb ObjectID constructor in case you need to use it
Usage example :
var Hapi = require("hapi");
var dbOpts = {
"url": "mongodb://localhost:27017/test",
"options": {
"db": {
"native_parser": false
}
}
};
var server = new Hapi.Server(8080);
server.pack.require('hapi-mongodb', dbOpts, function(err) {
if (err) {
console.error(err);
throw err;
}
});
server.route( {
"method" : "GET",
"path" : "/users/{id}",
"handler" : usersHandler
});
function usersHandler(request, reply) {
var db = request.server.plugins['hapi-mongodb'].db;
var ObjectID = request.server.plugins['hapi-mongodb'].ObjectID;
db.collection('users').findOne({ "_id" : new ObjectID(request.params.id) }, function(err, result) {
if (err) return reply(Hapi.error.internal('Internal MongoDB error', err));
reply(result);
});
};
server.start(function() {
console.log("Server started at " + server.info.uri);
});
Huge thanks to @dypsilon for his help into the making of this plugin.