@jenius2/j2-mongo-models
A Seed project for jenius 2 npm packages
Last updated 2 years ago by j2techlead .
UNLICENSED · Repository · Original npm · Tarball · package.json
$ cnpm install @jenius2/j2-mongo-models 
SYNC missed versions from official npm registry.

node-j2-mongo-models build status coverage report

A wrapper library to connect to mongodb, a special sauce for Jenius 2.

Description

Table of Contents

Install

npm install @jenius2/j2-mongo-models

Usage

1. Register as a hapi plugin

See the example below. More details on the plugin options are in the Plugin Options section.

const mongoDBModels = require('@jenius2/j2-mongo-models');
...

const plugins = [
  ...
  {
    register: mongoDBModels,
    options: {
      mongodb: {
        uri: dbUri,
        connectOptions: {}
      }
    }
  },
  ...
]

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

A common approach in our miroservices is to keep the database connection parameters as config, so that we can do this:

    {
      register: mongoDBModels,
      options: {
        mongodb: {
          uri: url.format({
            protocol: 'mongodb',
            hostname: Config.get('/resources/db/hostname'),
            port: Config.get('/resources/db/port'),
            auth: (Config.get('/resources/db/username') && Config.get('/resources/db/password')) ? `${Config.get('/resources/db/username')}:${Config.get('/resources/db/password')}` : '',
            pathname: Config.get('/resources/db/database'),
            slashes: true
          }),
          connectOptions: {}
        }
      }

2. Define the model

const { MongoModels } = require('mongo-db-connector');

class TransactionRequestModels extends MongoModels {
  static collection = 'transactions_request'
}

module.exports = TransactionRequestModels;

3. Then you can use it anywhere you want

const dbPlugin = server.plugins['@jenius2/j2-mongo-models'];
const db = dbPlugin.addModel('TransactionRequestModel', TransactionRequestModel);

... Example of usage:

  {
    return this.db.insertOne(doc)
    .then((result) => Object.assign({ id: result.insertedId }, doc));
  }

Connections

It is important to understand how the connections work for the plugin.

MongoClient.connect is used to connect

Please see: https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

We use the MongoClient.connect function to connect to the database. The uri and connectOptions are passed to this function. We do however default the connectOptions to:

{
  reconnectTries: 60,
  reconnectInterval: 1000,
  autoReconnect: true
}

An initial connection is established on plugin registration

The plugin will attempt to connect to the database on registration. This is the initial connection, which asserts we can hit the database. The timeout for this operation can be configured with the Plugin Options.

After the initial connection has been established, a connection pool is used

From this point on, the MongoClient connection pool is used. This means that a persistent connection to the database does not need to be maintained. Each request will use a connection in the pool. If the pool has no valid connections, it will attempt to re-establish a connection.

Plugin Options

The plugin can be configured with the following options:

{
  register: mongoDBModels,
  options: {
    mongodb: {
      uri: 'localhost:27017/mydb',
      debug: false,
      initialConnectOptions: {
        connectTimeoutMilliseconds: 60 * 1000,
        retryWaitMilliseconds: 500
      },
      connectOptions: {}
    }
  }
}
Option Usage
mongodb.uri Required. The connection string. Passed directly to MongoClient.connect.
mongodb.debug Optional. Default false. Print low-level debug messages.
mongodb.initialConnectOptions Optional. Options to control how the initial connection is established. Should not be needed in most cases.
mongodb.initialConnectOptions.connectTimeoutMilliseconds Optional. Default 60 * 1000. Total number of milliseconds which we allow to attempt to establish an initial connection.
mongodb.initialConnectOptions.retryWaitMilliseconds Optional. Default 500. Milliseconds to wait between initial connection attempts.
mongodb.connectOptions Optional. Connection options, passed directly to MongoClient.connect.

Current Tags

  • 1.0.2                                ...           beta (2 years ago)
  • 1.2.0                                ...           latest (2 years ago)

6 Versions

  • 1.2.0                                ...           2 years ago
  • 1.1.0                                ...           2 years ago
  • 1.0.2                                ...           2 years ago
  • 1.0.1                                ...           2 years ago
  • 1.0.0                                ...           2 years ago
  • 0.2.2                                ...           3 years ago

Copyright 2014 - 2016 © taobao.org |