这只是为了我的周末项目/学习,我对 Sinatra 和 MongoDB 非常陌生。
我已经为 mongoDB 安装了 gem,例如:mongo、mongo_mapper 和 mongoid。
当我尝试从 localhost 连接到 MongoHQ 上的数据库时,遇到了这样的错误:
Mongo::ConnectionFailure at /
failed to connect to any given host:port
* file: connection.rb
* location: connect
* line: 489
我找到了 a similar thread on SO ,但坦率地说,我不太明白答案......
这是我的代码片段:
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongo_mapper'
get '/' do
MongoMapper.connection = Mongo::Connection.new('flame.mongohq.com', 27044)
MongoMapper.database = 'notes'
MongoMapper.database.authenticate('foo', 'bar')
erb :list
end
我从 here 获取了上面的代码,但它似乎不起作用...
哪一部分错了?还有另一种方法可以做到这一点吗?最后,这个测试网络应用程序将部署到 heroku 上,所以我希望该解决方案可以与 localhost 和我的 heroku 服务器一起使用。
更新:
I just created a minimal code snippet to test the mongodb connection:
require 'rubygems'
require 'mongo'
db = Mongo::Connection.new("flame.mongohq.com", 27044).db("notes")
但是超时后还是报错:
$ ruby mongodbtest.rb
/Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:489:in
`connect': failed to connect to any given host:port (Mongo::ConnectionFailure)
from /Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:137:in
`initialize'
from mongodbtest.rb:4:in `new'
from mongodbtest.rb:4
主机名和端口是根据mongoHQ文档的,所以一定是对的。
提前感谢您的帮助。
第二次更新:
我刚刚使用终端测试了 mongodb 连接字符串:
mongo mongodb://flame.mongohq.com:27044/notes -u foo -p bar
不幸的是,这会给我一个连接失败错误,老实说,我不知道为什么......
最佳答案
我用
uri = URI.parse(ENV['MONGOHQ_URL'])
@mongo_connection = Mongo::Connection.from_uri( uri )
@mongo_db = @mongo_connection.db(uri.path.gsub(/^\//, ''))
@mongo_db.authenticate(uri.user, uri.password)
您可以使用 heroku config --long
命令查找您的 mongo 网址
关于Ruby Sinatra - 在 mongoHQ 上连接到 mongoDB 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3693490/