3
votes

Hi friends~ I wanna use MongoDB to implement a group based friendship model. Like Google Buzz. For example,
My name is Tom, Steve and Gavin are my friends. Steve is my classmate and coworker, Gavin is my coworker.

Tom
  -Group Classmates
     Steve
  -Group Coworkers
     Steve
     Gavin

My Question is how to design this schema?
In rails and Mongoid, I wrote the follow code:

Here is user.rb

class User
  include Mongoid::Document

  field :username
  field :email

  field :block_list, :type => Array, :default => []


  key :username

  embeds_many :groups

  embeds_many :pending_requests

  has_and_belongs_to_many :friends, :class_name => "User"

end

group.rb

class Group
  include Mongoid::Document
  embedded_in :user

  field :name

  field :members, :type => Array, :default => []
end

pending_request.rb


class PendingRequest
  include Mongoid::Document
  embedded_in :user

  field :username
  field :body
end

Any suggestions? Thank you.

1

1 Answers

1
votes

There are a few ways you could design a schema for this purpose. One of the important things to ask is this: If Tom says Gavin is a coworker, does that mean Gavin will also show Tom as a coworker?

Yes: If Either Tom or Gavin can create a link between the two of them and it's the same link either way (regardless of the process to create that link), then what you're really talking about is a relationship. Mongo is a NoSql database and doesn't do joins, so you would have to manage this relationship with multiple select and update queries. Tom could keep a list of coworkers and Gavin could keep a list of coworkers and any time either of them adds the other, both documents would need updated. In all honesty, this kind of relationship is what relational databases are good at. Mongo probably isn't the best solution.

No: If Tom can determine whether Gavin is a coworker completely independently of what Gavin thinks, then you should store an array of coworkers in your user collection. The same goes for classmates. Each user document would have a name field, a coworkers field, a classmates field, etc. To get Tom's info, you only need to pull a single document from a single collection and you have it all.

Keep in mind that tracking relationships between documents is not Mongo's strong suit. If you have a lot of relationships to deal with and relatively small documents, Mongo really isn't your best bet.

There's nothing wrong with using mySql to manage users and relationships, while storing activity logs, comments, posts, etc. in Mongo.