How check if field exists with firestore rules?

Viewed 3024

I have a firestore database with a collection of products and a collection of categories.

I want give at the user the delete permission on the categories collection only if the category document not have a products field.

the products field is an array of reference.

I have this rules:

match /shops/{shopId} {
  allow read: if true;
  allow write: if false;
  match /categories/{category=**}{      
    allow read: if true;
    allow write: if resource.data.products == null;
  }
}

But this rules not works, I cannot write or update a document.

2 Answers

Try this

match /shops/{shopId} {
  allow read: if true;
  allow write: if false;
  match /categories/{category=**}{      
    allow read: if true;
    allow create: if true;
    allow update, delete: if !('products' in resource.data);
  }
}

Using a helper Function as below

function hasProducts(){
  return resource.data.keys().hasAny(["products"])
}

match /shops/{shopId} {
  allow read: if true;
  allow write: if false;
  match /categories/{category=**}{      
    allow read: if true;
    allow write: if !hasProducts();
  }
}
Related