I want to add a super user to admin database from MongoDB using NodeJS. My first try is this:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var db = new Db('admin', new Server('locahost', 27017));
// Establish connection to db
db.open(function(err, db) {
if (err) { return console.log(err); }
console.log("Opened database");
// Add a user to the database
db.addUser('superuser', '1234', {
roles: [
"userAdminAnyDatabase",
"dbAdminAnyDatabase",
"clusterAdmin",
"readWriteAnyDatabase"
]
}, function(err, result) {
if (err) { return console.log(err); }
console.log("Added.");
});
});
When running the script I got this error:
[Error: failed to connect to [locahost:27017]]
And before this:
========================================================================================
= Please ensure that you set the default write concern for the database by setting =
= one of the options =
= =
= w: (value of > -1 or the string 'majority'), where < 1 means =
= no write acknowledgement =
= journal: true/false, wait for flush to journal before acknowledgement =
= fsync: true/false, wait for flush to file system before acknowledgement =
= =
= For backward compatibility safe is still supported and =
= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
= the default value is false which means the driver receives does not =
= return the information of the success/error of the insert/update/remove =
= =
= ex: new Db(new Server('localhost', 27017), {safe:false}) =
= =
= http://www.mongodb.org/display/DOCS/getLastError+Command =
= =
= The default of no acknowledgement will change in the very near future =
= =
= This message will disappear when the default safe is set on the driver Db =
========================================================================================
How can I fix the script to add the user superuser with password 1234 to admin database from MongoDB?
[Error: failed to connect to [locahost:27017]]it likely means that the problem occurs long before you try to create a new user. So when you wonder how to create a user, you are searching in the wrong direction.new Server('locahost', 27017), Do you see any problem here? Look closely! Typo in localhost name