It seems like Mongoid is now the superior ORM for Mongo based on performance and development activity. Unfortunately, we're on MongoMapper and need to migrate.
Are there any concerns or stumbling blocks we should be aware of? We have found a few outdated articles on Google and tried posting on the Mongoid Google Groups (though we were prohibited), but would love thoughts from SO members who have done this in the past.
We're on Rails 3.2.12.
Thanks!
Both of them are great MongoDB Libraries for Ruby. But if you want to switch, here are some notes:
Migrating MongoMapper ORM to Mongoid ORM - Notes
Configure the database connection.
Replace configuration yaml file(includes replica configuration).
Configure Mongoid specific options. e.g -
raise_not_found_error: false
. if you don't want an error every time a query returns nothing...Change all models definations -
include MongoMapper::Document
toinclude Mongoid::Document
Change the format for all fields definitions.
In mongoid, you should specipy the timestamp:
include Mongoid::Timestamps
Change validation. e.g:
:in => ARRAY
, will be:validates :name, presence: true, inclusion: { in: ARRAY }
Change indexes.
Change order_by format. e.g: MM:
Model.all(:order => 'name')
. Mongoid:Model.order_by('name ASC')
Error
is a keyword in Mongoid. So if you have a model namedError
, you should change it.Pagination format is different, using another gem.
The primary key index entry in MM is
id
. In Mongoid it's_id
, if you have other code relying on.id
in the object JSON, you can override as_json function in your Model to create the JSON structure you want.In MM,
Model.fields(:id, :name)
,limits the fields returned from the database to those supplied to the method. In Mongoid it'sModel.only(:name,:id)
Some queries changes:
Selecting objects by array: MM:
Model.where(:attr.in => [ ] )
andModel.where(:attr => [ ] )
. Mongoid is only:Model.where(:attr.in => [ ] )
Map option of MM is equivalent to the Mid's pluck.
Model.map(&:name)
--to--Model.pluck(:name)
Mongoid doesn't support find query for nil. e.g:
value = nil. Model.find(value)
will throw an error :"Calling Document .find with nil is invalid"
. So in mongoid we should do:Model.find(value || "")
.In MM:
Model.find_or_initialize_by_name("BOB")
. In MongoidModel.find_or_initialize_by(name: "BOB")
.MM can be used in those two options:
Model.where({:name => 'BOB'}).first
, and alsoModel.first({:name => 'BOB'})
. Mongoid has only first option.In MM, to update multiple objects:
Model.set({conditions},attr_to_update)
. In Mongoid:Model.where(conditions).update_all(attr_to_update)
.
来源:https://stackoverflow.com/questions/20849152/advice-on-migrating-from-mongomapper-to-mongoid