npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

hapi-multi-mongo

v5.1.1

Published

Hapi mongodb connection plugin, especially for multiple connections

Downloads

51

Readme

npm version Build Status

Hapi-Multi-Mongo

Battle tested Hapi mongodb connection plugin, especially for multiple connections

Supports Hapi >= 17

To use with older versions of Hapi, please use 3.1.1 version

Motivation

Motivation to create this plugin is accessing multiple MongoDB servers and various databases in request/reply life cycle. The plugin accepts complex configuration options and exposes/decorates connections object to the server object.

Connection options can be a single object with the following keys:

  • connection: Required. Single MongoDB connection uri (eg. mongodb://user:pass@localhost:27017/db_name) or an array of multiple servers. Connection configuration can be a string, object or an array combination of object and strings. You can find a detailed explanation of this configuration in Usage section. One simple tip here, you have to connect directly to a database, or you have to provide a connection name for each connection element, plugin stores and exposes connections through database name or a given name.
  • options: Optional. Provide extra settings for the connection, see MongoClient documentation. You can override this setting by providing additional connection options to each server.
  • decorate: Optional. Rather have exposed objects accessible through server and request decorations.
    • If true, server.mongo else request.mongo
  • name: Optional. Exposed name to server and request object if you want to access connections other than name mongo.
    • If myMongos, server.myMongos else request.myMongos

Acknowledgements

This module borrows from hapi-mongodb, thank you to @Marsup for his excellent work.

Installation:

npm install hapi-multi-mongo

Usage:

Configuration object options. All of the samples in below are correct

// single connection to db_name
// access with request.server.plugins['hapi-multi-mongo'].mongo.db_name
// you can pick a collection and query from this usage
{
    connection: 'mongodb://localhost:27017/db_name'
}
// single connection to db_name
// access with request.server.plugins['hapi-multi-mongo'].mongo.myConn
// in this usage, you have to pick a database first
// then you need to choose a collection then you can have queries on that collection,
// keep that in mind
{
    connection: {
      uri: 'mongodb://localhost:27017',
      name: 'myConn'
    }
}

// single with custom name
// access with request.server.plugins['hapi-multi-mongo'].mongo.myDb
{
    connection: {uri: 'mongodb://localhost:27017/db_name', name: 'myDb'}
}
// single with options
// access with request.server.plugins['hapi-multi-mongo'].mongo.db_name
{
    connection: {uri: 'mongodb://localhost:27017/db_name', options: {fsync: true}}
}

// single with decorate
// access with server.mongo.db_name, request.mongo.db_name
{
    connection: 'mongodb://localhost:27017/db_name',
    decorate: true
}

// single with decorate and custom name
// access with server.myMongos.db_name, request.myMongos.db_name
{
    connection: 'mongodb://localhost:27017/db_name',
    decorate: true,
    name: 'myMongos'
}

// multi server
// access with request.server.plugins['hapi-multi-mongo'].mongo.db_name
// request.server.plugins['hapi-multi-mongo'].mongo.db_name_2
{
    connection: [
        'mongodb://localhost:27017/db_name',
        'mongodb://localhost:27018/db_name_2'
    ]
}

// multi server with custom name
// access with request.server.plugins['hapi-multi-mongo'].mongo.db_name
// request.server.plugins['hapi-multi-mongo'].mongo.myDB
{
    connection: [
        'mongodb://localhost:27017/db_name',
        {uri: 'mongodb://localhost:27018/db_name', name: 'myDB'}
    ]
}

// multi server with decorate
// access with server.mongo.db_name, request.mongo.db_name
// server.mongo.myDB, request.mongo.myDB
{
    connection: [
        'mongodb://localhost:27017/db_name',
        {uri: 'mongodb://localhost:27018/db_name', name: 'myDB'}
    ],
    decorate: true
}

// multi server with options
// access with server.mongo.db_name, request.mongo.db_name with fsync: true
// server.mongo.myDB, request.mongo.myDB with fsync: false
{
    connection: [
        'mongodb://localhost:27017/db_name',
        {uri: 'mongodb://localhost:27018/db_name', name: 'myDB', options: {fsync: false}}
    ],
    decorate: true,
    options: {fsync: true}
}


// custom promise library
// access with server.mongo.db_name, request.mongo.db_name uses native mongo promise implementation
// server.mongo.myDB, request.mongo.myDB uses bluebird as a promise library
{
    connection: [
        'mongodb://localhost:27017/db_name',
        {uri: 'mongodb://localhost:27018/db_name', name: 'myDB', options: {promiseLibrary: require('bluebird')}}
    ],
    decorate: true
}
Example App:
const Hapi = require('@hapi/hapi');
const Boom = require('@hapi/boom');

const startServer = async function() {
    
    const dbOpts = {
        "connection": [
          "mongodb://localhost:27017/test",
          { uri: "mongodb://localhost:27017", name: "remoteMongo"}
        ],
        "options": {
            "native_parser": false
        }
    };
    
    const server = Hapi.Server();
    
    await server.register({
        plugin: require('hapi-multi-mongo'),
        options: dbOpts
    });
    
    // pick collection from database connection
    server.route( {
        "method"  : "GET",
        "path"    : "/users/{id}",
        "handler" : async (request, reply) => {
            const mongos = request.server.plugins['hapi-multi-mongo'].mongo;
            const collection = mongos['test'].db().collection('users');

            try {
                const result = await collection.findOne({  "_id" : request.params.id });
                return result;
            }
            catch(err){
                return Boom.internal('Internal MongoDB error', err)
            }
        }
    });
    
    // access directly to the mongo object and pick database and collection
    server.route( {
        "method"  : "GET",
        "path"    : "/dashboard",
        "handler" : async (request, reply) => {
            const mongos = request.server.plugins['hapi-multi-mongo'].mongo;
            const db = mongos.remoteMongo.db('analytics');
            const collection = db.collection('users');

            try {
                const result = await collection.find({});
                return result;
            }
            catch(err){
                return Boom.internal('Internal MongoDB error', err)
            }            
        }
    });

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

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