Mongodb – Schema design for privacy settings in MongoDB

mongodboptimizationschema

I have a set of documents that can have various privacy settings around them:

  1. They can be completed public (any registered user) can view them
  2. They can be viewable only by people following you (this
    "Followers" array is stored in each User's document)
  3. They can be private to the person who published the document as well.
  4. They can have custom privacy which allows you to name individual users who can view the document. In addition, you can allow groups of users to also view the document (e.g. there could be a group called "Sample Group" which has 20 users in it. You could allow said group to view the tile.)

I am lost as to how to implement a schema for this efficiently in MongoDB and would love some insight into best practices for implementing this schema.

Best Answer

It's important to remember that since there are multiple ways to design schema in MongoDB for a given set of data, it's critical to consider the types of reads and writes you will be making from your application.

Assuming that you will be querying for a subset of documents that a given user can see, it's likely that you will want to structure the document collection in a way that will give you the ability to query for all "visible" documents in a single query.

Document structure such as:

{ _id: ...,
  public: true,
  groups: ['group1', 'group2',...],
  users: ['user1','user2',...],
}

You could now query for all documents visible to user X if you have a list of groups user X belongs to by querying:

db.documents.find( { $or : [
     { public : true },
     { users  : X },
     { groups : { $in : [list-of-X's-groups] } }
] } )
Related Question