Advice on migrating from MongoMapper to Mongoid?

岁酱吖の 提交于 2019-12-04 02:45:19

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 to include 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 named Error, 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's Model.only(:name,:id)

  • Some queries changes:

    1. Selecting objects by array: MM: Model.where(:attr.in => [ ] ) and Model.where(:attr => [ ] ) . Mongoid is only: Model.where(:attr.in => [ ] )

    2. Map option of MM is equivalent to the Mid's pluck. Model.map(&:name) --to-- Model.pluck(:name)

    3. 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 || "").

    4. In MM: Model.find_or_initialize_by_name("BOB"). In Mongoid Model.find_or_initialize_by(name: "BOB").

    5. MM can be used in those two options: Model.where({:name => 'BOB'}).first, and also Model.first({:name => 'BOB'}). Mongoid has only first option.

    6. In MM, to update multiple objects: Model.set({conditions},attr_to_update). In Mongoid: Model.where(conditions).update_all(attr_to_update).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!