如何使用具有凭据的ruby连接到mongo?

时间:2017-08-18 17:54:45

标签: ruby mongodb

我正在尝试连接到具有凭据的数据库。我在网上找不到任何有用的信息......

require: 'mongo'

begin
   db = Mongo::Connection.new(" IP ADDRESS " , PORT ).db("COLLECTION")
   db.authenticate("username","password")


rescue StandardError => err
    abort("error")
end

C:/Ruby193/lib/ruby/gems/1.9.1/gems/mongo-1.8.2/lib/mongo/networking.rb:306:在`rescue in receive_message_on_socket':操作失败并出现以下情况异常:到达文件结尾(Mongo :: ConnectionFailure)

1 个答案:

答案 0 :(得分:1)

看起来有一个#add_auth方法以及auths可以传递给构造函数也许可以尝试

auths = [{"db_name" => "COLLECTION", 
          "username" => YOUR_USERNAME, 
          "password" => YOUR_PASSWORD}]
Mongo::Connection.new(" IP ADDRESS " , PORT, auths: auths)

OR

auth = {"db_name" => "COLLECTION", 
          "username" => YOUR_USERNAME, 
          "password" => YOUR_PASSWORD}
Mongo::Connection.new(" IP ADDRESS " , PORT).add_auth(auth)

并查看是否有效

参考Mongo::MongoClient::GENERIC_OPTSMongo::MongoClient#setup

BTW,这是宝石和红宝石的旧版本。你考虑过可能的升级吗?

Mongo的最新版本(截至目前)为2.4.3,选项现在更加透明,例如。

Mongo::Client.new("IP_ADDRESS:PORT", user: USERNAME, password: PASSWORD, auth_mech: AUTHENTICATION_MECHANISM)

虽然根据您的评论,我不确定身份验证是您的问题