-
-
Save betteryourweb/a26e60413e330efce398c35062f3d151 to your computer and use it in GitHub Desktop.
NodeJS - MongoDB - creating new user with admin privileges
This file contains hidden or 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 MongoClient = require('mongodb').MongoClient | |
// | |
// config | |
// | |
var mongoPort = '27017' | |
var mongoHost = 'localhost' | |
var dbName = 'dbName' | |
var userName = 'admin' | |
var userPassword = 'pass1' | |
// | |
// start | |
// | |
MongoClient.connect('mongodb://'+mongoHost+':'+mongoPort+'/'+dbName, | |
function(err, db) { | |
if (err){ | |
return console.log('Error: could not connect to mongodb') | |
} | |
// Use the admin database for the operation | |
var adminDb = db.admin() | |
// Add the new user to the admin database | |
adminDb.addUser(userName, userPassword, { | |
roles: [{ | |
role : "userAdmin", | |
db : dbName | |
}] | |
}, | |
function(err, result) { | |
if (err){ | |
return console.log('Error: could not add new user') | |
} | |
// Authenticate using the newly added user | |
adminDb.authenticate(userName, userPassword, function(err, result) { | |
if (err){ | |
return console.log('Error: could authenticate with created user') | |
} | |
console.log('Ok') | |
db.close() | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment