Home > Mobile >  Firebase retrieve a document based on grandchild's value which is a collection [duplicate]
Firebase retrieve a document based on grandchild's value which is a collection [duplicate]

Time:09-26

Is there a way to Query a collection which is a grandchild in firebase?

Current firebase structure:

{
  products: {
    "dfwojozijowjfoije": {
      "barcodes": ["12345", "5678"],
      "productName": "someProduct"
    },
    "sdafsdasdfasdfadsf": {
      "barcodes": ["99999", "88888"],
      "productName": "someProduct2"
    }
  }
}

Current Query that I use:

await firebase
            .database()
            .ref('products')
            .orderByChild('barcodes')
            .equalTo('88888')
            .on('value', snapshot => {
                    setProductName(snapshot.val())
                }
            )

CodePudding user response:

There is no way in a Firebase Realtime Database query to check for the existence of a value in an array. If you're trying to do this, it typically means that your data structure is actually not an array, but a set.

Since a set data type doesn't exist, you can't store it in Firebase natively though. The closest equivalent is not an array though, but a map like this:

"barcodes": {
  "12345": true,
  "5678": true
}

This may look a bit weird at first, but it has the exact properties that you're typically looking for in a set: the values (that are now keys) are by definition unique in the parent node, and you can test for the presence of a specific value/key.

Unfortunately, you still won't be able to query on this structure, as you can only define indexes on keys that you know, and I'm assuming that the barcodes are a rather infinite set of values.

So instead you'll have to define an inverted data structure, as I've explained here: Firebase query if child of child contains a value

  • Related