Last active
December 5, 2016 17:10
-
-
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
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
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