Skip to content

Instantly share code, notes, and snippets.

@gmlevit
Last active December 5, 2016 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmlevit/aebd88d36a80b7f5e13fd4ba6c7e4eab to your computer and use it in GitHub Desktop.
Save gmlevit/aebd88d36a80b7f5e13fd4ba6c7e4eab to your computer and use it in GitHub Desktop.
Function that creates a MongoDB database. It authenticates a db user or creates one if it doesn't exist
function createMongoDb(callback) {
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var dbName = 'testdb', dbHost = 'localhost', dbPort = '27017';
var dbUser = 'testuser', dbPassword = 'testpassword';
var db = new Db(dbName, new Server(dbHost, dbPort));
// Connect to the database
db.open(function (err, db) {
if (err) {
console.log(err);
callback();
}
else {
// Authenticate user (basically check if user exists)
db.authenticate(dbUser, dbPassword, function(err, result) {
// If error authenticating:
// user doesn't exist, so create user
if (err){
db.addUser(dbUser, dbPassword, {roles: ["dbOwner"]}, function(err, result) {
if (err){
console.log(err);
}
// close database connection
db.close();
callback();
});
}
// Otherwise, user exists
else{
// close connection
db.close();
callback();
}
});
}
});
}
// Calls function createMongoDb
createMongoDb(function() {
// Do something here
console.log('MongoDB database created');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment