Search code examples
iosfirebasefirebase-realtime-databaseunique-constraint

unique property in Firebase


I have an IOS app which contains categories. My storage on Firebase looks like this:

-root
   -Categories
      -key
        - color:
        - name:
        - sum:
   -Expenses
      -key
        -amount: 
        -category: 
        -date: 
        -description: 
        -initiator: 
        -name: 

User must not add a category twice. I want to make category name unique. Is it possible to do in Firebase? Thanks in advance.


Solution

  • There is no way to ensure unique values in the Firebase Database.

    But on the other hand keys are always unique within their context.

    You can make use of this to model your data in such a way that it guarantees uniqueness of the property you want. Say you want the category name to be unique, store the categories under their name:

    -Categories
      -name
        - color:
        - sum:
    

    With this structure you're guaranteed to have unique category names.

    If you must store the categories under their current keys, but still want to ensure unique names. You can create a secondary index, which uses the category names as keys to ensure their uniqueness.

    -Categories
      -key
        - color:
        - name:
        - sum:
    -CategoryNames
      -name: key
    

    This latter approach is explained further in Kato's answer to Enforcing unique usernames with Firebase simplelogin