firebasegoogle-cloud-firestorefirebase-security

Firebstore rules - Check SubCollection exist


I have a collection of musics. They can contain a subcollection of notes. I would like to prevent deletion if any notes exists

I tried

match /databases/{database}/documents {
 match /musics/{musicId} {                              
    allow delete: if request.auth.uid != null && 
      !exists(/databases/$(database)/documents/musics/$(musicId)/notes);
 }
}

But here firestore does not allow delete at all.


Solution

  • What you're trying to do isn't possible without adding more information to your system.

    Firstly, Firestore doesn't have a sense of whether or not a collection (or subcollection) "exists". A document merely includes a collection or subcollection name in its path, and documents including those names either exist or not on their own terms. There is no operation that can tell you if a collection has documents or not, other than querying it directly to see what it contains. However, with security rules, you can't query a collection, so this is not possible at all.

    One alternative is to maintain a count of the documents in your "notes" subcollection, store it as a field in another document (maybe in the "music" document directly), and use that document data to determine if the "music" document may be deleted.

    See also: