A simple Hapi MongoDB connection plugin, accessing one or several connections pools through server or request properties
MIT License
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 :
mongodb://user:pass@localhost:27017
).
mongodb://localhost:27017
true
, server.mongo
or request.mongo
server.<string>
or request.<string>
Several objects are exposed by this plugin :
client
: MongoClient
for that connection. If an array was provided for the configuration, it will be an array of MongoClient
s in the same orderdb
: Db
for that connection. If an array was provided for the configuration, it will be an array of Db
s in the same orderlib
: mongodb library in case you need to use itObjectID
: mongodb ObjectID constructor in case you need to use itUsage 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);
});
Ships with mongodb
6.x.