官术网_书友最值得收藏!

Mongoid ODM

Using a low-level driver to connect to the MongoDB database is often not the most efficient route. All the flexibility that a low-level driver provides is offset against longer development times and code to glue our models with the database.

An ODM (Object Document Mapper) can be the answer to these problems. Just like ORMs, ODMs bridge the gap between our models and the database. In Rails, the most widely used MVC framework for Ruby, Mongoid, can be used to model our data in a similar way to Active Record.

Installing the gem is similar to the Mongo Ruby driver, by adding a single file in the Gemfile:

gem 'mongoid', '~> 6.1.0'

Depending on the version of Rails, we may need to add the following to application.rb as well:

config.generators do |g|
g.orm :mongoid
end

Connecting to the database is done through a config file, mongoid.yml. Configuration options are passed as key-value pairs with semantic indentation. Its structure is similar to the database.yml used for relational databases.

Some of the options that we can pass through the mongoid.yml file are:

 

The next step is to modify our models to be stored in MongoDB. This is as simple as including one line of code in the model declaration:

class Person
include Mongoid::Document
End

We can also use the following:

include Mongoid::Timestamps

We use it to generate created_at and updated_at fields in a similar way to Active Record. Data fields do not need to be declared by type in our models but it's a good practice to do so. The supported data types are:

  • Array
  • BigDecimal
  • Boolean
  • Date
  • DateTime
  • Float
  • Hash
  • Integer
  • BSON::ObjectId
  • BSON::Binary
  • Range
  • Regexp
  • String
  • Symbol
  • Time
  • TimeWithZone

If the types of fields are not defined, fields will be cast to the object and stored in the database. This is slightly faster but doesn't support all types. If we try to use BigDecimal, Date, DateTime, or Range we will get back an error.

主站蜘蛛池模板: 宁武县| 嘉义市| 德令哈市| 桃园市| 永济市| 灌云县| 咸丰县| 蕲春县| 巧家县| 丰城市| 兰溪市| 斗六市| 类乌齐县| 玉山县| 武威市| 吉木乃县| 赫章县| 射洪县| 兰溪市| 香河县| 兴业县| 邛崃市| 广州市| 疏附县| 深泽县| 桃园市| 芷江| 湘阴县| 大港区| 麻城市| 阳泉市| 大同县| 六枝特区| 巴林左旗| 吴川市| 阳西县| 桃园县| 阆中市| 新巴尔虎左旗| 秦安县| 鹿邑县|