如何从NodeJS添加Mongo管理数据库中的用户?

时间:2013-12-13 08:51:20

标签: node.js mongodb

我想使用NodeJS从MongoDB向admin数据库添加超级用户。我的第一次尝试就是:

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.");
    });
});

运行脚本时出现此错误:

  

[Error: failed to connect to [locahost:27017]]

在此之前:

========================================================================================
=  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           =
========================================================================================

如何修复脚本以将用户superuser与密码1234添加到MongoDB的admin数据库?

1 个答案:

答案 0 :(得分:1)

你的错误在于这一行:

 var db = new Db('admin', new Server('locahost', 27017));
你打错了。你的意思是localhost