Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dmitryame/899851 to your computer and use it in GitHub Desktop.
Save dmitryame/899851 to your computer and use it in GitHub Desktop.
followers association with mongoid twitter style
What is the best way to model user/follower (twitter style) relationships with mongo? Most prominent solution is to embed an array of followers ids in every user object. I'm an idealist, and believe that if we are modeling twitter, we eventually will run into a situation when a user has millions of followers which will blow. The relational many_to_many is not easy to model with mongo, mongo_id tries to offer some implementation of basic associations, but the many_no_many, or has_many through is not there yet and I doubt it ever will be.
My solution is a compromise between relational normalization and "embed everything in one document".
class User
include Mongoid::Document
include Mongoid::Timestamps
# user will have many followerships, each will embedd a follower user,
# the user_id is stored on the followership object
references_many :followerships
end
class Followership
include Mongoid::Document
include Mongoid::Timestamps
# the user_id is stored on this object, which defines the parent user object which is being followed
referenced_in :user
# embedded user object is a follower
embeds_one :follower, :class_name=>"User"
end
@TylerLH
Copy link

TylerLH commented Apr 24, 2012

Did you ever try this method in production? Curious if you've got any performance results to share

@dmitryame
Copy link
Author

Not really, it was all theoretical, and it was never really put in prod.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment