Last active
January 22, 2017 21:35
-
-
Save crizstian/5a974183bd208611b5f2c9ea0ed0c9a0 to your computer and use it in GitHub Desktop.
Example of how to connect to a mongodb 3.4 replica set from nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MongoClient = require('mongodb') | |
// here we create the url connection string that the driver needs | |
const getMongoURL = (options) => { | |
const url = options.servers | |
.reduce((prev, cur) => prev + `${cur.ip}:${cur.port},`, 'mongodb://') | |
return `${url.substr(0, url.length - 1)}/${options.db}` | |
} | |
// mongoDB function to connect, open and authenticate | |
const connect = (options, mediator) => { | |
mediator.once('boot.ready', () => { | |
MongoClient.connect( getMongoURL(options), { | |
db: options.dbParameters(), | |
server: options.serverParameters(), | |
replset: options.replsetParameters(options.repl) | |
}, (err, db) => { | |
if (err) { | |
mediator.emit('db.error', err) | |
} | |
db.admin().authenticate(options.user, options.pass, (err, result) => { | |
if (err) { | |
mediator.emit('db.error', err) | |
} | |
mediator.emit('db.ready', db) | |
}) | |
}) | |
}) | |
} | |
module.exports = Object.assign({}, {connect}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment