简体   繁体   中英

How do you get an item from Realtime Database where you need to look into a child and check if the array has the id you are looking for

It's easier to explain through an example.

The data in question is:

data : { 

cluster1 : { 
id: 123 
things: [153, 525, 743] 
},

cluster2 : { 
id: 124 
things: [113, 547, 124] 
},

}

And we want to find all clusters that have things containing '547', which case should return the whole of cluster2.

I know how to do this in firestore, it would look something like this:

  db.collection("data")
        .where("things", "array-contains", userInput)

But for certain reasons I can't use firestore.

Does anyone know if there is a way to do it in Firebase Realtime Database.

Thank you!

There is no equivalent to Firestore's array-contains in the Realtime Database API. The closest you can get is to store the data as a map, with true as their value:

data : { 
  cluster1 : { 
    id: 123 
    things: {
      "153": true, 
      "525": true,
      "743": true
    } 
  },
  cluster2 : { 
    id: 124 
    things: {
      "113": true, 
      "547": true, 
      "124": true
    } 
  },
}

Now you can define an index on each property in things , and then use that in your query: ref.orderByChild("things/113").equalTo(true) .


Since the values in your things array are likely dynamic and not predefined, you won't be able to defined indexes for them. In that case you'll need to add an inverted data structure, that maps thing IDs back to clusters.

For an example of this, see Firebase query if child of child contains a value

For more on this topic, also see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM