3

i am getting an error of

Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "WkJymEhTtvgtIzQZZxs3VUTbmLh2quan" at /Products to your security rules for better performance.

this is my code:

firebase.database().ref("Products").orderByChild(user.uid + "quan").startAt(0).on('value', function (s) {
        var cartNum = 0;
        s.forEach(function (d) {
          console.log(d.child(user.uid + "quan").val());
          cartNum += d.child(user.uid + "quan").val();
        });
        $("#cartCount").text(cartNum);
      });

am trying to query products that has user.uid+ 'quan' in my firebase database

and this is the structure of my JSON ---->>>

image of my json structure

many thanks if someone can help me out

my security rules image

Anthony
  • 53
  • 1
  • 6

1 Answers1

1

As described in the documentation on indexing data and in the error message, you will need to add an index to the Firebase rules for your database in the console:

{
  "rules": {
    "Products": {
      ".indexOn": "WkJymEhTtvgtIzQZZxs3VUTbmLh2quan"
    }
  }
}

This will solve the error message for the current user. The problem is that you will need to declare such an index explicitly for each UID, which is not feasible unless you have a specific set of users in mind.

The underlying problem is that your current data structure makes it easy to find a user for a given product, but it does not make it easy to find the products for a specific user. To allow the latter use-case, you'll want to add an additional data structure for that inverted mapping, sometimes referred to as a reverse or inverted index:

"Users": {
  "uid1": {
    "productId1": true,
    "productId2": true
  },
  "uid2": {
    "productId3": true,
    "productId4": true
  }
}

While this duplicates some data, it allows you to look up the related data in both directions. This type of data duplication to allow use-cases is quite common in NoSQL databases.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • ok, i will try this out and get back to you when it's resolved, thanks – Anthony Aug 22 '20 at 12:37
  • i created another index for cart items and added some wildcards `$unknown` to my security rule for jumping over dynamic node, it solved thanks alot – Anthony Aug 23 '20 at 09:07