mongodb many to many without join table

109 Views Asked by At

Originally, I specified a relationship where contact has_many services. Therefore, services has a foreign key of contact_id:

class Contact
  include Mongoid::Document
  field :name, type: String
end

class Service
  field :name, type: String
  field :contact_id, type: Integer
end

Now there is a possibility to add an additional contact to a service, so service has many contacts. However, the contacts that are added are ones that already exist independently. So I do not want to embed one entity inside another. A contact and service will always live independently. No embedding.

So should I just store the ids of the contacts inside an array of Service? In other words, my new models will look like this:

class Contact
  include Mongoid::Document
  field :name, type: String
end

class Service
  field :name, type: String
  field :contact_id, type: Integer
  field :contact_ids, type: Array, default: []
end

Or is there a better solution to address the many to many problem here (without embedding one document in another)?

1

There are 1 best solutions below

0
On BEST ANSWER

For the Many-To-Many, you don't have 36 options : you actually have 2 :

  • Array of IDs on One side like you did
  • Array of IDs on Both sides.

The cool thing with the "both sides" solution is that you can find query documents from both collections to get the links.

Example with books and authors :

db.books.findOne()
{
    _id: 1,
    title: "The Great Gatsby",
    authors: [1, 5]
}

db.authors.findOne()
{
    _id: 1,
    firstName: "F. Scott",
    lastName: "Fitzgerald",
    books: [1, 3, 20]
}