danwillm
danwillm

Reputation: 497

Querying with two array with firestore security rules

I currently have two arrays in a single document, one representing product ids and the other representing user ids. In my query, I need to query both of the arrays for firestore security rules to work correctly, but to do that, I tried using array-contains and in in the same query, which is acceptable in the documentation, but when I go to query, I get "missing or insufficient permissions".

db.collection('Depots')
  .where("products", "array-contains", productId)
  .where("users", "in", "lk9asdn340fk3fvb")
  .get();

This is my security rule:

function uidAndProductInDocument() {
    return request.auth.uid in resource.data.users;
}

This is what the contents of the document looks like:

enter image description here

However, even this security rule fails and does not return anything, even though there are docs in the database that should be returned, as they match the parameters.

I'm not sure how to secure the product relationship, as that relation for the product-user is in another document, and I have tried another approach in my other question, which can be found here: Firestore security rules: get() use in hasAny() list method

Is there anything that I am missing or need to do for this query to work?

Thanks in advance.

Upvotes: 1

Views: 586

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317412

You should consider restructuring your data in order to support the query you need. Since Firestore can't perform two array-contains queries, one of your arrays should be converted to an object, where the keys are values of the array, and the field value is simply true. For example, you could take your users list and make it look like this for each user:

users: {
  xxxx: true
  yyyy: true
}

Now you can query like this:

db.collection('Depots')
  .where("products", "array-contains", productId)
  .where(`users.${uid}`, "==", true)
  .get();

And your rule can check like this:

return resource.data.users[request.auth.uid]

Upvotes: 2

Related Questions