Search code examples
mongodbscalingrelationnosql

How would a nosql schema be designed to relate users to "friends" who are actually other users?


User {
    _id: "my_user",
    name: "john smith",
    email: "blah@test.com,
    friends: [
      *More Users*
    ]
}

Do I rewrite the User data of friends? Everytime I "add a friend" do I put in the data again or do I "relate" to another User _id field?


Solution

  • Your document structure should be based on your data access patterns i.e. the way that your program will access the data. In the example you've given above you're dealing with a one to many relationship because there will only be one "John Smith" to many friends. Friends of "John Smith" could be friends with each other which you can deal with by using Friends '_id', placed within an array as you've done so. This will reduce the risk of anomalies when modifying the data.

    User1 {
      _id: "my_user1",
      name: "john smith",
      email: "blah@test.com,
      friends: [
        "my_user2",
        "my_user3",
        "my_user4",
      ]
    }
    
    User2 {
      _id: "my_user1",
      name: "john smith",
      email: "blah@test.com,
      friends: [
        "my_user1",
        "my_user3",
        "my_user4",
      ]
    }
    

    Another option is to embed the data but this could lead to duplicates and modification anomalies so should be avoided unless you need to do it for performance reasons.