Scott Dietrich
Scott Dietrich

Reputation: 686

Firebase Query - Nested Data

I am attempting to query some hierarchical data in firebase. I'm having a little difficulty in figuring out how to query the following data structure:

{
  "orgs": {
    "-KBFXBBEyvgtfqMvU4pi": {
      "name": "ACME 123",
      "owner": "-K9IPqIUIuEFzLS0f_Pe",
      "users": {
        "-KBF_GhwTmXfR6Jce30t": {
          "email": "[email protected]",
          "permission": "editor",
          "userKey": "K99LV9cTjh1ovW1D5j2"
        },
        "-KBF_M533zzbUilGvAAW": {
          "email": "[email protected]",
          "permission": "editor"
        }
      }
    },
    "-KBFaKlJ8tfqjBQjAZgq": {
      "name": "ACME Alt LLC",
      "owner": "-K9IPqIUIuEFzLS0f_ZZ",
      "users": {
        "-KBFbD4trt9nyeHPUQbn": {
          "email": "[email protected]",
          "permission": "editor"
        }
      }
    }
  }
}

Specifically, I would like to find out if the email address "[email protected]" exists. But this is a little confusing for me since I need to search through 2 levels (orgs and users).

Upvotes: 0

Views: 399

Answers (1)

Scott Dietrich
Scott Dietrich

Reputation: 686

After reading some more documentation it seems I really shouldn't be nesting my data like this. I'll be honest, it seems kind of contrary to do this when working with a JSON schema that that is hierarchical. Anyway, this is what I'm looking to do now:

{
  "orgs": {
    "-KBFXBBEyvgtfqMvU4pi": {
      "name": "ACME 123",
      "owner": "-K9IPqIUIuEFzLS0f_Pe"
      }
    },
    "-KBFaKlJ8tfqjBQjAZgq": {
      "name": "ACME Alt LLC",
      "owner": "-K9IPqIUIuEFzLS0f_ZZ"
      }
    }
  },
  "orgMembership": {
    "-KBFXBBEyvgtfq7h381h": {
      "org": "-KBFXBBEyvgtfqMvU4pi",
      "email": "[email protected]",
      "permission": "editor"
  }
}

Then I can use the following query:

orgMRef.orderByChild("email").equalTo("[email protected]").once("child_added", function(snapshot) {
  console.log("found: " + snapshot.key());
});

Upvotes: 1

Related Questions