Last active
May 30, 2017 09:27
-
-
Save alces/62e4af6182d9cf56b1af4562ac545bea to your computer and use it in GitHub Desktop.
Add user to MongoDB (if no admin user exists, first create it)
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
var ADMIN_USER = 'root'; | |
var ADMIN_PASS = 'ass4' + ADMIN_USER | |
var NEW_USER = 'dummy'; | |
var TARGET_DB = 'mydb'; | |
var conn = new Mongo(); | |
var admDb = conn.getDB('admin'); | |
try { | |
admDb.createUser({user: ADMIN_USER, | |
pwd: ADMIN_PASS, | |
roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]}); | |
} catch (err) { | |
if (! /not authorized/.test(err.message)) { | |
throw err; | |
} | |
} | |
admDb.auth({user: ADMIN_USER, pwd: ADMIN_PASS}); | |
var db = conn.getDB(TARGET_DB); | |
if (! db.getUser(NEW_USER)) { | |
db.createUser({user: NEW_USER, | |
pwd: 'ass4' + NEW_USER, | |
roles: [{role: 'readWrite', db: TARGET_DB}]}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment