1

I'm trying to figure out how, if possible, to query a specifically named child node in all instances of a parent node in Firebase. It can be assumed that all parent nodes queried have this specifically named child node in it.

In this example, uid is a unique identifier for each user and I'm trying to get a list of displayNames:

{
  users: {
    uid: {
      displayName: "stringOfSomeKind"
    }
    uid2: {
      displayName: "moreStrings"
    }
    uid3: {
      displayName: "evenMoreStrings"
    }
    ...
  }
}

The purpose of this is so I can check to see if a displayName is currently taken. (I can't use the displayName as the primary key because when a user logs in, I'll only have the uid available.)

How can I efficiently check to see if one of these displayNames is already taken? Do I have to denormalize my data to do so efficiently? If so, how?

Zachary Espiritu
  • 937
  • 7
  • 23

2 Answers2

3

Firebase world is quite different!

When such scenarios come you have to think to redesign your database structure, In your case uid is unique identifier so is displayName- speaking technically.

You will have to maintain additional data like:

{
  users: {
    uid: {
      displayName: "stringOfSomeKind"
    }
    uid2: {
      displayName: "moreStrings"
    }
    uid3: {
      displayName: "evenMoreStrings"
    }
    ... 
  }
 displayNames: {
        "display_name": "uid",
        "display_name2": "uid2",
        "display_name3": "uid3"
     ...      
 }
}

Happy Helping!

Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
  • What are the pros and cons of doing a .indexOn displayName instead of denormalizing something as simple as this? Which approach would be better? – anthonypliu Jul 05 '17 at 20:03
1

When you load a node from Firebase, you also get all data under that node. Assuming that you have more data per user than just their display name, that can indeed lead to needlessly loaded data.

If you only want to load a list of display names, you should indeed store a list of display names.

{
  displayNames: {
    "stringOfSomeKind": "uid",
    "moreStrings": "uid2",
    "evenMoreStrings": "uid3"
  }
}

If you come from a background of relational/SQL databases, this may seem unnatural at first. For me it helped to realize that these structures are indexes, same as the "index by displayName" that you might add to your relational database. The difference is that in NoSQL/Firebase it is your code that maintains the index, while in most RDBMSs such indexes are maintained by the system.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Yeah, I'm more used to relational databases. I saw this structure somewhere else and I was confused somewhat—your answer makes complete sense though. Thanks so much! – Zachary Espiritu Feb 07 '16 at 16:37