Mongo :: OperationFailure – 使用from_uri时需要登录

我的目标是连接我的heroku / mongolab数据库,但我不断收到此错误:

Mongo::OperationFailure at /mongotest/a/b : need to login file: networking.rb location: send_message_with_gle line: 89 

我正在使用的代码是:

 client = Mongo::MongoClient.from_uri(ENV['MONGOLAB_URI']) db = client.db('test') testcoll = db['testcoll'] testcoll.insert({:'_id' => "def", :'test' => "woop de doop"}) testcoll.find() 

ENV['MONGOLAB_URI']=mongodb://heroku_app########:password@ds0xxxxx.mongolab.com:xxxxx/heroku_app########

我知道uri是正确的,包含用户名和密码,为什么会出错呢? 此外,错误发生在insert()行,而不是我validation的行。

Welp,结果是url将我连接到heroku_app########数据库,但我正在尝试访问名为test的数据库,所以显然我没有通过身份validation。 本来不错的Mongo返回了一个错误,指出我已登录但未登录到正确的数据库。 那好吧。

我没有足够重视uri的格式,这是

 mongodb://username:password@host:port/database 

事实certificate,数据库部分……非常重要。

(我在编写测试时实际上找到了答案,但是如果这个答案已经存在,那可能会让我节省大量的时间,所以我再次写它并自己回答。)