Skip to content

Instantly share code, notes, and snippets.

@alces
Last active May 30, 2017 09:27
Show Gist options
  • Save alces/62e4af6182d9cf56b1af4562ac545bea to your computer and use it in GitHub Desktop.
Save alces/62e4af6182d9cf56b1af4562ac545bea to your computer and use it in GitHub Desktop.
Add user to MongoDB (if no admin user exists, first create it)
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