What exactly is the difference between has_many, has_and_belongs_to_many and embeds_many in mongoid?
mongodb, mongoid, ruby, ruby-on-rails
Solution
Mongoid's documentation is quite clear:
Embedded relations describe documents who are stored inside other documents in the database.
Referenced relations describe documents that reference documents in another collection by storing foreign key data (usually an id) about the other document in itself.
In detail:
Referenced 1-n / `has_many`
When defining a relation of this nature, each document is stored in its respective collection, but the child document contains a "foreign key" reference to the parent.
# The parent band document.
{ "_id" : ObjectId("4d3ed089fb60ab534684b7e9") }
# The child member document.
{
"_id" : ObjectId("4d3ed089fb60ab534684b7f1"),
"band_id" : ObjectId("4d3ed089fb60ab534684b7e9")
}
Referenced n-n / `has_and_belongs_to_many`
When defining a relation of this nature, each document is stored in its respective collection, and each document contains a "foreign key" reference to the other in the form of an array.
# The band document.
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"tag_ids" : [ ObjectId("4d3ed089fb60ab534684b7f2") ]
}
# The tag document.
{
"_id" : ObjectId("4d3ed089fb60ab534684b7f2"),
"band_ids" : [ ObjectId("4d3ed089fb60ab534684b7e9") ]
}
Embedded 1-n / `embeds_many`
Documents that are embedded using the `embeds_many` macro are stored as an array of hashes inside the parent in the parent's database collection.
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
"albums" : [
{
"_id" : ObjectId("4d3ed089fb60ab534684b7e0"),
"name" : "Violator",
}
]
}
Problem
I understand this not a programming problem, I am unable to find a very clear and descriptive solution.