Giter VIP home page Giter VIP logo

hapi-mongodb's Introduction

npm version Build Status

Hapi-MongoDB

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 :

  • url: Optional. MongoDB connection string (eg. mongodb://user:pass@localhost:27017).
    • defaults to mongodb://localhost:27017
  • settings: Optional. Provide extra settings to the connection, see documentation.
  • decorate: Optional. Rather have exposed objects accessible through server and request decorations. You cannot mix different types of decorations.
    • If true, server.mongo or request.mongo
    • If it's a string, 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 MongoClients in the same order
  • db : Db for that connection. If an array was provided for the configuration, it will be an array of Dbs in the same order
  • lib : mongodb library in case you need to use it
  • ObjectID : mongodb ObjectID constructor in case you need to use it

Usage 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);
});

Compatibility level

  • Hapi >= 20
  • Node.js >= 18

Ships with mongodb 6.x.

hapi-mongodb's People

Contributors

cht8687 avatar dominiklessel avatar ecwillis avatar iamdoron avatar jdrames avatar manuel-reil avatar marsup avatar midnightcodr avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

hapi-mongodb's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • mongo 6
npm
package.json
  • joi ^17.13.1
  • mongodb ^6.6.2
  • @hapi/code ^9.0.3
  • @hapi/hapi ^21.3.9
  • @hapi/hoek ^11.0.4
  • @hapi/lab ^25.2.0
  • sinon ^18.0.0
  • @hapi/hapi >= 20.3.0
  • node >= v18
nvm
.nvmrc
  • node 18

  • Check this box to trigger a request for Renovate to run again on this repository

Access plugin from another file

In previous versions of Hapi, I could export the server. Then, in an included file, I could do var Db = Server.plugins['hapi-mongodb'].db; to get access to the Db registered in the plugin.

However, Hapi 6.X does not seem to support this. I know you can do request.server.plugins['hapi-mongodb'].db;, but how can you access the plugin when not using request?

For example,

I want to authenticate but my scheme doesn't give me access to the request. So, in my authentication, I need access to the db. How can this be accomplished?

ESM import * as mongo

Hi,

When I use

import * as mongo from "hapi-mongodb" and use mongo to register like follows:

await server.register({
plugin: mongo,
options: dbOpts,
});

then I have to use: request.server.mongo.db to make this work instead of request.mongo.db

Any explanation as to why this would happen?

Readme fails to mention the async nature of mongodb connections

In the readme it fails to mention that any code that needs the db connection immediately (such as running unit tests via hapi server injection) needs to wait on the server.pack.require callback or else you get a race condition.
I would file a PR for this but not sure how you want to word such a note. If you dont care, I will be happy to take a swing at it!

Question - Access named databases

Hello,

I am wondering if there is any option to access the databases through name instead of array position.

I'm talking about this particular option:

db : connection object to the database, if an array was provided for the configuration, it will be an array of connections in the same order

I would prefer to provide an object (or hashmap) of configurations and then be able to access them through database name.

Another question is, if I use the decorate option can I expect it to work the same way? I mean, I can access one of the DBs by reques.server.mongo.db[1] ?

getting error while doing the npm install for hapi-mongodb

npm WARN package.json [email protected] No repository field.
npm ERR! registry error parsing json
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\nodejs\node.exe" "C:\nodejs\node_modules\npm\bin\npm-cli.js" "install"
npm ERR! node v0.12.7
npm ERR! npm v2.11.3

npm ERR! Unexpected token <
npm ERR!
npm ERR!
npm ERR! <title>404 - Path /hapi-mongodb not found in group repository "npm" [id=npm].</title>
npm ERR!
npm ERR!
npm ERR!
npm ERR!
npm ERR!
npm ERR!
npm ERR!
npm ERR!
npm ERR!

404 - Path /hapi-mongodb not found in group repository "npm" [id=npm].


npm ERR!

Path /hapi-mongodb not found in group repository "npm" [id=npm].


npm ERR!
npm ERR!
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
npm ERR! C:\hapi-mongo-api-master\npm-debug.log

Ability to access other types from database besides ObjectID

Does this plugin have the ability to access types like string, int, etc from mongodb? In your example you show the retrieval of elements in your database based on ObjectID, but lets say I was trying to search for a specific string in my database and query all the elements connected to that string, like so:

server.route({
    method: 'GET',
    path: '/test/cuisines/{cuisine}',
    handler: function(request, reply) {
        var db = request.server.plugins['hapi-mongodb'].db;
        var result = request.server.plugins['hapi-mongodb'].String;

        db.collection('restaurants').findOne({"cuisine": new result(request.params.cuisine)}, function(err, result) {
            if(err) {
                return reply(Boom.internal('Internal MongoDB error', err)); 
            }
            reply(result);
        });
    }
});

db.collection is undefined

when using the db object, I get collection as undefined.

I am loading the plugin with Glue as well, if that matters.

At that point, the db objects value is...

EventEmitter {
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s: 
   { databaseName: 'DBName.REDACTED',
     dbCache: {},
     children: [],
     topology: 
      EventEmitter {
        domain: null,
        _events: [Object],
        _eventsCount: 7,
        _maxListeners: undefined,
        s: [Object],
        bson: [Getter],
        isMasterDoc: [Getter],
        poolSize: [Getter],
        autoReconnect: [Getter],
        host: [Getter],
        port: [Getter],
        emitOpen: false,
        connectTimeoutMS: 30000,
        socketTimeoutMS: 0 },
     options: 
      { read_preference_tags: null,
        readPreference: [Object],
        native_parser: false,
        url: 'mongo://MONGO_URL.Redacted',
        promiseLibrary: [Function: Promise] },
     logger: { className: 'Db' },
     bson: {},
     authSource: undefined,
     readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined },
     bufferMaxEntries: -1,
     parentDb: null,
     pkFactory: undefined,
     nativeParser: false,
     promiseLibrary: [Function: Promise],
     noListener: false,
     readConcern: undefined },
  serverConfig: [Getter],
  bufferMaxEntries: [Getter],
  databaseName: [Getter],
  options: [Getter],
  native_parser: [Getter],
  slaveOk: [Getter],
  writeConcern: [Getter] }

server.decorate?

It would be nice to just be able to type server.db (or server.mongodb) instead of server.plugins['hapi-mongodb'].db;. It seems like plugins like chairo are doing that vs expose.

hapi 8.x.x

Is plugin going to be updated to hapi version 8?

Is there any way to access the DB object not in the request?

I'm curious if there is a way to access the DB object without having to get it from the request object?

In your example, you have your controller coupled with your DAO layer so it makes sense to get the DB object from the request, but in my project I have my controller separated from my DAO layer and I hate to have to pass the DB object to the DAO method b/c that's just a bad practice.

Example of my separation of controller/dao:

controller:

var caseDao = require('./case-dao');

module.exports = function() {

  return {
  findLevel1Data: function findLevel1Data(req, reply) {

      caseDao.findLevel1Data(req.server.plugins['hapi-mongodb'].db, function(err, data) {

        if (err) {
          return reply(Boom.badImplementation(err));
        }

        reply(data);
      });
    }
});

dao:

module.exports = function() {

  return {

    /**
     * Finds all the level 1 data
     */
    findLevel1Data: function findLevel1Data(db, callback) {
        // DO DAO STUFF HERE. THE CONTROLLER SHOULDN'T NEED TO KNOW HOW THE DAO ACCESS DATA A.K.A SHOULDN'T HAVE TO PASS THE DB OBJECT.
    }
}();

Hapi v17 Support

Overview

If you are not aware yet, Hapi v17 is making the transition from callbacks to async/await, as well as deprecating some other rarely used functionality. This is a breaking change that may make your plugin no longer compatible with the Hapi API.

Changelog

Draft release notes can be found here: hapijs/hapi#3658

Target Release

The target release date for v17 is the beginning of November.

Tasks

  • Reply to this to acknowledge that you are actively maintaining this module and are willing to update it
  • Update plugin to be fully async/await compatible using the v17 branch from Hapi for testing

    Possible dev flow for updating

    • Clone Hapi
    • npm link within the Hapi repo
    • npm link hapi within your plugin repo
    • Your plugin will now be using v17 of Hapi branch for tests
  • Release new major version of your plugin on npm. Please use a major version increment as this will be a breaking change and it would be terrible for it to sneak into current versions of Hapi.

Notes

  • Support is being dropped for all versions of Node <8.0.0.
  • Hapi v16 will continue to be supported for as long as there exists a Node LTS actively being supported that is not compatible with v17.
  • Targeted release date is November 1st, 2017. Please try to have your plugin updated before then.
  • This issue is being opened because your plugin is listed on the official hapi website

Options deprecation warning

I get following message when registering hapi-mongodb

...
server.register({
  register: require('hapi-mongodb'),
  options: dbOpts
}, function (err) {
...
the server/replset/mongos options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl, ... ]

I am using:

  • Hapi-MongoDB 6.2.0
  • MongoDB 3.2.8
  • Hapi 16.1.0
  • Node.js 6.9.2
  • Windows 7

Error: Cannot start server before plugins finished registration

I am getting Error: Cannot start server before plugins finished registration

my code:

`const Hapi = require('hapi');
var Boom = require("boom");

const dbOptions = {
url: "mongodb://localhost:27017/comparekaro",
settings: {
db: {
native_parser: false
}
}
}

const server = new Hapi.Server();

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

server.connection({
port : 3001,
router : {
stripTrailingSlash : true,
},
routes : {
cors : true,
}
});

server.route({
method: 'GET',
path: '/',
handler: (request, reply) => {
var db = request.server.plugins['hapi-mongodb'].db;
var ObjectID = request.server.plugins['hapi-mongodb'].ObjectID;

db.collection('catalogs').find((err, result) => {
  if (err) return reply(Boom.internal('Internal MongoDB error', err));
  reply(result);
});

}
});

server.route({
method: 'GET',
path: '/{name}',
handler: (request, reply) => {
reply(i am ${request.params.name});
}
});

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

Bump to mongodb 3.x.x

Just an issue to note all things related to the upgrade.

There seems to be a few quirks with MongoClient.connect, especially the fact that it doesn't error when it doesn't manage to connect, and also the fact it changed the return type.

Bump to mongodb 3.6.3

We're in the process of moving our node up to v14 and noticed a notices:

circles-api_1      | (node:193) Warning: Accessing non-existent property 'count' of module exports inside circular dependency
circles-api_1      |     at emitCircularRequireWarning (internal/modules/cjs/loader.js:650:11)
circles-api_1      |     at Object.get (internal/modules/cjs/loader.js:664:5)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/db_ops.js:16:42)
circles-api_1      |     at Module._compile (internal/modules/cjs/loader.js:1063:30)
circles-api_1      |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
circles-api_1      |     at Module.load (internal/modules/cjs/loader.js:928:32)
circles-api_1      |     at Function.Module._load (internal/modules/cjs/loader.js:769:14)
circles-api_1      |     at Module.require (internal/modules/cjs/loader.js:952:19)
circles-api_1      |     at require (internal/modules/cjs/helpers.js:88:18)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/collection_ops.js:5:23)
circles-api_1      | (node:193) Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency
circles-api_1      |     at emitCircularRequireWarning (internal/modules/cjs/loader.js:650:11)
circles-api_1      |     at Object.get (internal/modules/cjs/loader.js:664:5)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/db_ops.js:17:44)
circles-api_1      |     at Module._compile (internal/modules/cjs/loader.js:1063:30)
circles-api_1      |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
circles-api_1      |     at Module.load (internal/modules/cjs/loader.js:928:32)
circles-api_1      |     at Function.Module._load (internal/modules/cjs/loader.js:769:14)
circles-api_1      |     at Module.require (internal/modules/cjs/loader.js:952:19)
circles-api_1      |     at require (internal/modules/cjs/helpers.js:88:18)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/collection_ops.js:5:23)
circles-api_1      | (node:193) Warning: Accessing non-existent property 'remove' of module exports inside circular dependency
circles-api_1      |     at emitCircularRequireWarning (internal/modules/cjs/loader.js:650:11)
circles-api_1      |     at Object.get (internal/modules/cjs/loader.js:664:5)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/db_ops.js:18:43)
circles-api_1      |     at Module._compile (internal/modules/cjs/loader.js:1063:30)
circles-api_1      |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
circles-api_1      |     at Module.load (internal/modules/cjs/loader.js:928:32)
circles-api_1      |     at Function.Module._load (internal/modules/cjs/loader.js:769:14)
circles-api_1      |     at Module.require (internal/modules/cjs/loader.js:952:19)
circles-api_1      |     at require (internal/modules/cjs/helpers.js:88:18)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/collection_ops.js:5:23)
circles-api_1      | (node:193) Warning: Accessing non-existent property 'updateOne' of module exports inside circular dependency
circles-api_1      |     at emitCircularRequireWarning (internal/modules/cjs/loader.js:650:11)
circles-api_1      |     at Object.get (internal/modules/cjs/loader.js:664:5)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/db_ops.js:19:46)
circles-api_1      |     at Module._compile (internal/modules/cjs/loader.js:1063:30)
circles-api_1      |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
circles-api_1      |     at Module.load (internal/modules/cjs/loader.js:928:32)
circles-api_1      |     at Function.Module._load (internal/modules/cjs/loader.js:769:14)
circles-api_1      |     at Module.require (internal/modules/cjs/loader.js:952:19)
circles-api_1      |     at require (internal/modules/cjs/helpers.js:88:18)
circles-api_1      |     at Object.<anonymous> (/home/app/src/node_modules/mongodb/lib/operations/collection_ops.js:5:23)
circles-api_1      | [hapi-mongodb,info] MongoClient connection created for {"url":"mongodb://mongo:27017/circlesv3","decorate":true,"settings":{"useNewUrlParser":true,"useUnifiedTopology":true}}

Seems bumping this helped: firstandthird@7f05dd1#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519R23

I made some other changes there before realizing we had forked this. If you want I can get a pr to bump just mongodb.

Promises

Promises are now supported by the NodeJS core driver for mongodb. Is hapi-mongodb going to support promises too?

mongodb needs to be a peerDependency

In the application I am building, I can't seem to get hapi-mongodb to work unless I npm install it as a peerDependency.

I believe that the current way works fine in smaller applications, but in larger ones the references get messed up.

My current application requires go:
Main application -> business logic plugin -> hapi-mongodb

Could just be a quirk of my environment, but probably worth looking in to.

Example in Read Me not working.

I have tried the exact same example on my computer, but getting the following error.

Debug: hapi, internal, implementation, error
TypeError: Uncaught error: Cannot read property 'plugins' of undefined
at usersHandler

usersHandler is my handler to reply get request.
npm module is added.
collection "usrers" available in db "test".
query is executable in mongo shell.

Thanks for any help.

Hapi v17 support

Will this plugin be supported in hapi v17? It's listed as an official plugin in the hapi website.

Mongodb Native Driver 2.1.20 issues

Hi, this is more a discussion than an issue.

I am using Mongodb 3.0.12 (wiredTiger), nodeJS 6.x, for my fairly large hapi application, running on Ubuntu 14.04.

The native driver bundled with hapi-mongodb right now is 2.1.20 but it has some breaking changes. We found that after some time, a particular database (we have 3-4 mongo databases deployed on a large machine, all running on port 27017, with different urls) stops responding to queries without throwing any sort of error.

So we downgraded the nodejs-mongodb driver to the last known working version 2.1.4 (used in the dev environment) and thankfully mongo started throwing MongoError: topology was destroyed. So we changed the plugin options, while registering, to define values of keepAlive and connectTimeoutMS in socketOptions. That seemed to work for now. (In case someone else has the same issue).

The point of all of this is to understand that even though it's a driver issue, shouldn't we bundle hapi-mongodb with a working version of the native mongo driver, instead of version 2.x.x?

Is there anyone else who encountered the same issue?

Hapi 6.x not working with example

It was all working fine for me with Hapi 5, but I just installed Hapi 6 and now I get an error.

server.pack.require('hapi-mongodb', dbOptions, function (err
^
TypeError: Object [object Object] has no method 'require'

Can you please update the example code. Thanks.

Creation of indexes

Hi,

First, thanks for this wonderful Hapi plugin. I would like to initialize indexes and maybe run various operations before the server is actually started (or right after it is started). How can I access the plugin/db after the server has been registered? The plugin is injected into the "server" variable in my routes, but I can't access it anywhere else (or before that). Would be perfect if I could use it before my server.start(). Is there a way?

Always returning 404

I am trying to utilize this plugin but always getting 404.

I can tell it is getting to the correct db.

Do you have a working demo that can be shared or have you seen this before.

Thanks


Below is my configuration
const dbOptions = {
url: 'mongodb://localhost:27017/db',
settings: {
poolSize: 10
},
decorate: true
};

const manifest = {
'connections': [
{
'port': 3000,
'labels': ['api'],
'host': 'localhost'
}
],
'registrations': [
{
'plugin': {
'register': '.'
},
'plugin': {
'register': 'hapi-mongodb',
'options': dbOptions

        }
    }
]

};

Glue.compose(manifest, options, function(err, server) {
server.start(function(err) {
if(err) {
throw err;
}
console.log('server running at: ' + server.info.uri);
});
});

`

Compatability with mongodb 4.0

Is this compatible with MongoDB 4? We're using Atlas - set up a new DB on 4 - and while the DB connects, I can't read any data from it. No errors - just an empty array is returned.

I'm able to view, and query the db in 3T.

Thanks
Rob

2.3 changed to 3.0

The API for 2.3 was a breaking change from 2.1 (options changed to settings in the in the dbOpts object), it seems like 2.3 should have been labelled 3.0 to ensure safety for consumers.

Any chance the tag can be updated to 3.0 and 2.3 removed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.