mongoose-helpers-connection
v0.1.4
Published
returns a mongoose connection promise
Downloads
5
Maintainers
Readme
mongoose-helpers-connection
returns a mongoose connection promise.
note: you can use mongoose-helpers-setup-db instead of using this module directly.
table of contents
notes
logging
- error events will be logged to the console
- additional logging - if
options.connection.debug
is set totrue
the following events will also be logged to the console- connected
- connecting
- disconnected
- open
- reconnected
errors
- if an error occurs, the error will be attached to the db object as
db.error
.
installation
npm install mongoose-helpers-connection
usage
var express = require( 'express' )
var connection = require( 'mongoose-helpers-connection' )
var mongoose = require( 'mongoose' )
var app = express()
var User = new mongoose.Schema(
{
displayName: String,
email: String,
id: String,
photo: String
}
)
var options = {
connection: {
debug: config.debug,
uri: {
database: config.database,
password: config.password,
username: config.username
}
},
schemas: [
{
'User': User
}
]
}
function setupDb( options ) {
return connection( options.connection )
.then(
function ( db ) {
try {
if ( Array.isArray( options.schemas ) ) {
options.schemas.forEach(
function ( schema ) {
var keys = Object.keys( schema )
db.model( keys[ 0 ], schema[ keys[ 0 ] ] )
}
);
}
return db;
} catch ( err ) {
throw err
}
}
)
.catch(
function ( err ) {
throw err
}
)
}
setupDb( options )
.then(
function ( db ) {
app.db = db
}
)
.catch(
function ( err ) {
app.db = {
error: err
}
}
)
// elsewhere in your app
app.db.model( 'User' )
.findOne(
{ 'id': id },
function( err, existing_user ) {}
)