Skip to content

Instantly share code, notes, and snippets.

@betteryourweb
Forked from foull/mongo-create-user.js
Created October 10, 2018 17:46
Show Gist options
  • Save betteryourweb/a26e60413e330efce398c35062f3d151 to your computer and use it in GitHub Desktop.
Save betteryourweb/a26e60413e330efce398c35062f3d151 to your computer and use it in GitHub Desktop.
NodeJS - MongoDB - creating new user with admin privileges
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