3.1.0 • Published 8 years ago

hapi-mongojs v3.1.0

Weekly downloads
11
License
MIT
Repository
github
Last release
8 years ago

hapi-mongojs

NPM version Build Status codecov.io

A tiny plugin to share a common MongoDB connection pool across the whole Hapi server using mongojs and ensure collection indexes.

Setup

npm install --save hapi-mongojs

Run the example

# remember to start MongoDB
npm run example:install
npm run example:start

# verify if server is running
http://localhost:8888/status
# run the example
http://localhost:8888/example

Example

const Hapi = require('hapi');
const Boom = require('boom');
// IMPORT NPM DEPENDENCY
const mongojs = require('hapi-mongojs');

// ADD PLUGINS CONFIG
const plugins = [
  {
    register: mongojs,
    options: {
      url: 'mongodb://localhost:27017/myDatabase',
      // ENSURE COLLECTION INDEXES (OPTIONAL)
      collections: [{
        name: 'myCollection1',
        indexes: [{
          keys: {
            'aField': 1
          },
          options: {
            'unique': true,
            'name': 'afield_idx'
          }
        }]
      }]
    }
  }
];

const server = new Hapi.Server();

server.connection({
  host: 'localhost',
  port: 8888
});

server.route([
  {
    method: 'GET',
    path: '/example',
    handler: function (request, reply) {

      // GET DB CONNECTION
      const myCollection = mongojs.db().collection('myCollection1');

      // EXECUTE A QUERY
      myCollection.find((error, value) => {
        if (error) {
          return reply(Boom.badData('Internal MongoDB error', error));
        }
        reply(value);
      });

    }
  }
]);

server.register(plugins, (err) => {
  if (err) {
    console.error(err);
    throw err;
  }

  server.start((err) => {
    if (err) {
      console.error(err);
      throw err;
    }
    console.log('info', `Server running at: ${server.info.uri}`);
  });
});
3.1.0

8 years ago

3.0.1

10 years ago

3.0.0

10 years ago

2.1.0

10 years ago

2.0.0

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago

0.1.1

10 years ago

0.1.0

10 years ago