chpr-mongodb
![codecov](https://codecov.io/gh/transcovo/chpr-mongodb/branch/master/graph/badge.svg?token=TTjxBMcFBQ)
MongoDB connector
MIGRATIONS GUIDELINES
This library is a wrapper on node-mongodb-native
.
The original documentation is available here. The purpose is to help
having robust connection on MongoDb databases potentially on multiple
databases, with models definitions and migration patterns.
Requirements
async
/ await
is required (Node.js 7+)MongoDB 3.2+
is required to use the document validation
feature
Configuration
Overall configuration
The connector configuration object must look like this:
{
databases: [
]
}
By default, all indexes are created in background. You can change this
behavior by setting the property ensureIndexInBackground
to false
.
Database connection configuration
If you want to connect a specific database, please use the following object
format:
{
name: 'riders',
url: 'mongodb://localhost:27017/riders',
options: {
}
}
The options
properties are documented in the official documentation.
Instanciation
Simple connection
const MongodbConnector = require('chpr-mongodb');
async function start() {
const client = new MongodbConnector({
databases: [{
name: 'test',
url: 'mongodb://localhost:27017/test'
}]
});
await client.connect();
}
async function stop() {
await client.disconnect();
}
Models definitions
Please have a look to the example.
const MongodbConnector = require('chpr-mongodb');
async function start() {
const client = new MongodbConnector({
databases: [{
name: 'test',
url: 'mongodb://localhost:27017/test'
}]
}, {
users: {
DATABASE: 'test',
COLLECTION: 'users'
}
});
await client.connect();
await client.migrate('update', 'init');
}
async function stop() {
await client.disconnect();
}
Migrations definitions
Please have a look to the migrations documentation.
const addUniqueIndexExample20171129 = require('./1.add-unique-index-example.js');
module.exports = new Map([
['1', addUniqueIndexExample20171129]
]);
const MongodbConnector = require('chpr-mongodb');
const migrations = require('./migrations');
async function start() {
const client = new MongodbConnector({
databases: [{
name: 'test',
url: 'mongodb://localhost:27017/test'
}]
}, {
users: {
DATABASE: 'test',
COLLECTION: 'users'
}
}, migrations);
await client.connect();
await client.migrate('update', '1');
}
async function stop() {
await client.disconnect();
}
Installation
nvm i
npm install
Tests
npm run mocha
npm run eslint
npm run mocha
npm test