Home > Software engineering >  Firebase tree structure
Firebase tree structure

Time:04-22

I am trying to create an application that manages shopping lists. A shopping list has users and products. Which way should I use to create the JSON tree structure:

"ShoppingLists": {
  "ShoppingListId" : {
    "name" : "String",
    "description": "String",
    "imageUrl": "String",
    "Users" : {
      "User1Id" : {
        "username" :"String",
        "photoUrl" : "String"
      },
      "User2Id" : {
        "username" :"String",
        "photoUrl" : "String"
      }
    },
    "Products" : {
      "ProductId1" : {
        "name" : "String",
        "productPhotoUrl" : "String"
      }
    }
  }

This is the first option

"ShoppingLists": {
  "ShoppingListId" : {
    "name" : "String",
    "description": "String",
    "imageUrl": "String",
    "Users" : {
      "UserId1" : "String", 
      "UserId2" : "String"
    },
    "Products" : {
      "ProductId1" : "String"
    }
  }

And this is the second one. In the second option I get the username and the photoUrl using the userId.

Which one is better or are both of them bad?

CodePudding user response:

There is no objective "better" for a NoSQL database design; it all depends on the use-cases of your app.

That said, a common antipattern is to nest multiple types of data under a single branch of your JSON tree. A more regular structure would be to separate those out into their own top-level branches, with the same keys:

"ShoppingLists": {
  "ShoppingListId" : {
    "name" : "String",
    "description": "String",
    "imageUrl": "String",
  }
},
"ShoppingListUsers" : {
  "ShoppingListId" : {
      "User1Id" : {
        "username" :"String",
        "photoUrl" : "String"
      },
      "User2Id" : {
        "username" :"String",
        "photoUrl" : "String"
      }
    },
  }
},
"ShoppingListProducts" : {
  "ShoppingListId" : {
    "Products" : {
      "ProductId1" : {
        "name" : "String",
        "productPhotoUrl" : "String"
      }
    }
  }
}

Now you can read all shopping lists, without having to also read the users and products in each shopping list. Plus, this way you can have separate security rules for the lists themselves, their users, and their products.

Note that I'm intentionally not focusing on what you store for each user/product in a shopping list, but merely on the nesting of data types.

To learn more about this, also see:

  • Related