Mongoid is an object document mapper (ODM) for MongoDB that allows developers to work with MongoDB documents as objects. Some key features of Mongoid include defining document schemas with fields and associations like references and embeds, validation support, indexing, integration with Rails caching and authentication frameworks like Devise, and dropping down to the lower-level MongoDB driver when needed for performance. Mongoid aims to provide an everyday ORM solution for MongoDB along with features for testing, searching, and file uploads.
10. class Post
include Mongoid::Document
include Mongoid::Timestamps
field :title
field :content
field :published_on, :type => DateTime
field :slug
end
13. class Person
include Mongoid::Document
field :first_name
field :last_name
embeds_one :address
end
class Address
include Mongoid::Document
field :street
field :city
embedded_in :person, :inverse_of => :address
end
26. RSpec Integration
# in spec/spec_helper.rb
RSpec.configure do |config|
config.mock_with :rspec
config.before :each do
Mongoid.master.collections.select {|c| c.name !~ /
system/ }.each(&:drop)
end
end
32. Works out of the box
FactoryGirl.define do
factory :post do
title 'My first blog post'
author 'Kevin Faustino'
content 'Hello World'
end
end
33. Factories with Cucumber
# features/support/env.rb
require 'factory_girl'
require 'factory_girl/step_definitions'
34. Monkey Patched Step Definition
# features/step_definitions/mongoid_steps.rb
Given /^an? (.+) exists with an? (.+) of "([^"]*)"$/
do |model, field, value|
factory_name = model.gsub(' ', '_')
Factory factory_name, field => value
end
35. Example Feature Usage
Given the following posts exist:
| title | excerpt |
| 10 greatest Batman Villians | We countdown ... |
| The Death of Batman | Batman falls ... |
37. Create a Cache-Key
module Cacheable
def cache_key
if new_record?
"#{collection_name}/#{id}/new"
elsif respond_to?(:updated_at)
"#{collection_name}/#{id}-#{updated_at.to_i}"
else
"#{collection_name}/#{id}"
end
end
end
39. post = Post.safely(:w => 2).create(
:title => 'We will receive verification'
)
post.safely(:w => 2).destroy
40. Safely Options
:w - A client can block until a write
operation has been replicated to N servers
:fsync - force the database to fsync all files
before returning
42. Query from your Slaves
# Query specific
Post.where(:title => 'Toronto Ruby').enslave
# Document specific
class Post
include Mongoid::Document
enslave
end
44. When you need more
performance, drop down
to the driver
45. collection = mongo-ruby-driver
# Add a post id only if it does not already exist on
# the set
collection.update({'_id' => id}, {'$addToSet' =>
{'post_ids' => post.id}})
53. Document Example
class Post
include Mongoid::Document
include Mongoid::Timestamps
field :title
field :author
field :content
field :slug
referenced_in :blog
mount_uploader :featured_image, ImageUploader
end