【问题标题】:how to authenticate mongoose connection mongodb in node.js如何在node.js中验证猫鼬连接mongodb
【发布时间】:2014-12-28 23:06:50
【问题描述】:

我已经用命令创建了 mongodb 用户

use admin
db.createUser(
    {
      user: "superuser",
      pwd: "12345678",
      roles: [ "root" ]
    }
)

然后在我的应用程序中,我尝试像这样连接猫鼬

var options = {
user: "superuser",
pass: "12345678"
};


var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';

mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);

var User = mongoose.model('User');

通过猫鼬插入数据时出现此错误

MongoError: not authorized for insert on twitter-mongo.users

请告诉我我的代码有什么问题

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这工作正常:

    var options = { server: { socketOptions: { keepAlive: 1 } } };
    var connectionString = 'mongodb://admin:admin1234@localhost:27017/myDB';
    
     mongoose.connect(connectionString, options);
    
    //Add those events to get more info about mongoose connection:
    
    // Connected handler
    mongoose.connection.on('connected', function (err) {
      console.log("Connected to DB using chain: " + connectionString);
    });
    
    // Error handler
    mongoose.connection.on('error', function (err) {
      console.log(err);
    });
    
    // Reconnect when closed
    mongoose.connection.on('disconnected', function () {
       self.connectToDatabase();
    });
    

    【讨论】:

    • 这似乎已被弃用。
    【解决方案2】:

    您必须在连接字符串中声明 authSource 参数才能指定包含您的用户凭据的数据库的名称:

    var options = {
      user: "superuser",
      pass: "12345678"
    };
    
    var mongooseConnectionString = 'mongodb://localhost/twitter-mongo?authSource=admin';
    

    注意:对于 Mongoose 4.x 的用户,您可能还希望在 options 对象中包含 useMongoClient: true。这会使 请使用带有身份验证凭据的 MongoClient.connect 进行身份验证open() 已弃用 错误消息。

    【讨论】:

    • 谢谢。我为此苦了好几个小时:)
    • 在 mongoose 5.x 中不再需要 useMongoClient 选项,请删除它。
    【解决方案3】:

    试试这个

    const mongooseConnectionString = 'mongodb://superuser:12345678@ localhost/twitter-mongo?authSource=admin'
    

    【讨论】:

      【解决方案4】:

      我确实使用 docker 运行了一个 mongo 服务,然后用这段代码将我的 mongoose 连接到它

      const _database = 'mongodb://user:pass@localhost:port/MyDB?authSource=admin';
      mongoose.connect(_database, {
          useNewUrlParser: true
      })
      .then(() => console.log('Connected to MongoDB ...'))
      .catch(err => console.error('Could not connect to MongoDB:‌', err));
      

      这等于

      mongo --username user --password pass --authenticationDatabase admin --port 27017
      

      连接后使用MyDB数据库对其进行查找、聚合、插入等操作。

      如果您的数据库没有用户(MongoDB 默认用户),那么您可以更改 Database,如下所示:

      const _database = 'mongodb://localhost:port/MyDB';
      

      27017 是默认的 MongoDB 端口,如果您的 MongoDB 端口也没有更改,那么您也可以对端口执行相同的操作。 像下面这样:

      const _database = 'mongodb://localhost/MyDB';
      

      这和下面的一样:

      mongo
      

      上面的代码是因为没有用户也没有端口,所以不是用户也不需要认证数据库。

      【讨论】:

        【解决方案5】:

        您需要在您正在操作的数据库中创建一个用户,而不是管理数据库。

        使用这个命令,

        use twitter-mongo;
        db.createUser({
          user: "superuser",
          pwd: "12345678",
          roles: [ "root" ]
        });
        

        取而代之的是,

        use twitter-mongo
        db.createUser({
          user: "superuser",
          pwd: "12345678",
          roles: [ "root" ]
        });
        

        【讨论】:

          【解决方案6】:
          mongoose.createConnection('mongodb://username:password@35.238.xxx.xxx:27017/dashboards?authSource=admin', {
             useNewUrlParser: true
          }, (e) => {
          
              if (e) throw console.error('Error connecting to mongo database master');
              console.log('Connected to mongo database master.');
          
          });
          

          【讨论】:

          • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
          【解决方案7】:

          创建连接字符串的正确方法是 var connection = mongoose.createConnection("mongodb://username:pwd@hostip:port/dbname?authSource=admin", options);

          请使用 authSource=admin 在连接字符串中进行身份验证。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-12-09
            • 1970-01-01
            • 2013-12-03
            • 2016-04-29
            • 1970-01-01
            • 1970-01-01
            • 2017-12-08
            相关资源
            最近更新 更多