Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Connecting to MongoDB in Node.js using 10gen's default driver
// use 10gen's mongodb driver
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
db;
// These variables can be passed in from the commmand line or defined in your environment
var mongoServer = process.env.PETAR_MONGODB_DB_HOST,
mongoPort = process.env.PETAR_MONGODB_DB_PORT,
mongoDb = process.env.PETAR_DB_NAME,
mongoUser = process.env.PETAR_MONGODB_DB_USERNAME,
mongoPass = process.env.PETAR_MONGODB_DB_PASSWORD;
// Print out the environment variables to make sure they exist
console.log(mongoServer, mongoPort, mongoDb, mongoUser, mongoPass);
// Initialize the server connection object
var server = new Server(mongoServer, mongoPort, {});
db = new Db(mongoDb, server);
// Open the connection
db.open(function(err, client) {
// Authenticate the user
client.authenticate(mongoUser, mongoPass, function(err, success) {
if (err) {
console.log('error connecting to MongoDB: ', err);
}
else {
// Do Something ...
console.log('successfully auth to open MongoDB: ', success);
}
});
});
@flynsequeira

This comment has been minimized.

Copy link

@flynsequeira flynsequeira commented Sep 3, 2018

How do you set process.env variables on terminal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.