Teodor Ciuraru
Teodor Ciuraru

Reputation: 3477

Firebase query by value in nested nodes

This is my document:

enter image description here

Let's say I have access to the following keys and values: 29 August 2018, 14:00 - 15:00 and vyMDLD3V6paRWiA7Xlp12zanT7h1. How can I combine those in query so that I get the parent key -LKVpa_1QviUn1RFlEPr?

I tried several versions:

  1. queryByValue, where value is equal to the id.
  2. queryByKey, where key is equal to 29 August 2018
  3. queryByChild, where child is equal to 29 August 2018

I got zero results or the entire document.

The end goal is to delete these nodes, so if you know any other method to do this (besides searching the database for the parent IDs then deleting), I would appreciate!

Upvotes: 0

Views: 129

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

You can do:

ref.queryOrdered(byChild: "29 August 2018/14:00 - 15:00")
   .queryEqual(toValue: "vyMDLD3V6paRWiA7Xlp12zanT7h1")

With ref pointing to bookedCourtsDaily. This will work, but for efficient execution it requires that you define an index on each timeslot. So in your rules you'll need something like:

{  
  "bookedCourtsDaily": {
    "$date": { 
      ".indexOn": ["13:00 - 14:00", "14:00 - 15:00", "15:00 - 16:00"] // etc
    }
  }
}

If this doesn't work for you, I'd recommend the more common approach of creating an inverse lookup in your JSON:

{
  "codeToAppointment": {
    "vyMDLD3V6paRWiA7Xlp12zanT7h1": "29 August 2018/14:00 - 15:00",
    "anotherCode": "28 August 2018/11:00 - 12:00"
  }
}

With this structure you can look up the path to an appointment from the "code" (or whatever else the meaning of the value in the JSON is).

Data duplication like this is quite common in NoSQL databases like Firebase.

Upvotes: 1

Related Questions