mongootils

Promisified connection utils for Mongoose

Usage no npm install needed!

<script type="module">
  import mongootils from 'https://cdn.skypack.dev/mongootils';
</script>

README

mongootils

Build Status

Promisified (Bluebird) connection utils for Mongoose

Requirements

mongootils requires Mongoose as a peer dependency, so make sure you have it installed in your project.

Installation

npm i --save mongootils

Usage

var Mongootils = require('mongootils');

var db = new Mongootils('mongodb://localhost/database');
db.connect()
.then(function(connection){
  console.log('Connected to ' + db.getConnectionURI());
  return db.disconnect();
})
.then(function(uri){
  console.log('Disconnected from ' + uri);
});

Using ExpressJS

var Mongootils = require('mongootils');
var app = require('express')();

var db = new Mongootils('mongodb://localhost/database');
db.connect()
.then(function(connection){
  console.log('Connected to ' + db.getConnectionURI());
  app.set('db', db);
});

// In another place...
app.get('/api/users', function(req, res){
  var db = req.app.get('db');
  var User = db.model('User');
  // ...
});

API

new Mongootils(NativeConnection connection)

var db = new Mongootils(mongoose.connections[3]);

new Mongootils(uri, options)

The same arguments as mongoose.connect or mongoose.createConnection).

var db = new Mongootils('mongodb://localhost/mongootils_test', { /* mongoose options object */ });

db.connect()

Returns a Bluebird promise that is resolved when the connection has been effectively opened, or rejected otherwise.

db.disconnect()

Returns a Bluebird promise that is resolved when the connection has been effectively closed, or rejected otherwise.

db.is()

Checks for the underlying connection state.

if (db.is('connecting') || db.is('connected')) {
  // Listen to Thin Lizzy
} else {
  // ... or listen to Thin Lizzy
}

db.getConnection()

Retrieves the underlying NativeConnection object.

db.getConnectionURI()

Returns the mongoose-valid connection URI for the underlying connection.

  var db = new Mongootils('mongodb://localhost:27000,127.0.0.1:27001/my_db');
  console.log(db.getConnectionURI()); // prints 'mongodb://localhost:27000/my_db,mongodb://127.0.0.1:27001/my_db'

TODO

  1. Test multiple connections to the same database with two different Mongootils object
  2. Test multiple database URI

Contributions

  1. Code feature
  2. Write tests
  3. Pull Request