Why am I getting the error "db_name must be a string or symbol"?
Quick version (for those familiar with Mongoid & Sinatra): If it's not the Psyche/Syck YAML-parsing issue, why else might I get this error when trying to connect to a MongoDB database using Mongoid? (Or maybe it is that issue, in which case, how do I fix my mongoid.yml file, posted below?)
More detailed (original) version:
I have a Sinatra app interacting with a MongoDB database via Mongoid:
configure do
Mongoid.load!('config/mongoid.yml')
end
And my mongoid.yml file looks like this:
development:
host: localhost
database: project_development
test:
host: localhost
database: project_test
production:
uri: <%= ENV['MONGOLAB_URI'] %>
Whenever I try to interact with the database in some way, I get the error db_name must be a string or symbol.
Now, I have found plenty of information on Google about this; but everything I can find seems to indicate that the problem has to do with Ruby now using the Psyche YAML parser instead of the old Syck parser. I don't think that's actually relevant in my case开发者_JS百科 because, as far as I can tell, the above YAML should be perfectly parsable by either.
(For what it's worth, though, I have tried using the YAML::ENGINE.yamler= 'syck'
trick, to no avail. I got the exact same error message.)
When I change the configuration to this:
Mongoid.configure do |config|
name = "project_development"
host = "localhost"
config.master = Mongo::Connection.new.db(name)
end
...then everything works fine. So I know that MongoDB is working on my machine. It's specifically when I use a YAML file that things go awry.
So what gives?
Make sure that ENV['RACK_ENV']
is set properly, as that is what Mongoid.load!
uses if it doesn't find Rails.env
.
I had the same problem with rails and solved it in this way :
The Problem lies in the different expectations of Mongoid and MongodbLogger concerning the structure of the mongoid.yml. Short : just add the database in addition on the upper level :
development:
sessions:
default:
database: apollo_development <<<< for the rest
hosts:
- localhost:27017
options:
consistency: :strong
database: apollo_development <<<<main level for logger
.... more stuff for the logger
The advantage is that you can use a database for your data and another for the logger. Technical there are two independant systems using the yml : the logger and MongoId.
精彩评论