Greg Johnston
Greg Johnston

Reputation: 28

Can I query a collection as part of a Cloud Firestore security rule?

I have a collection (DocumentRevisionLog) made up of documents that include a lastRevision field and a docId field. I want to reject a create/update if the document's lastRevision is less than the total number of documents with the same docId.

I'd like to write something like this

function lastRevision() {
    return request.resource.data.lastRevision;
}
match /DocumentRevisionLog/{change} {
   allow create, update: if lastRevision() >= 
     // line below is what I'm curious about
     db.collection('DocumentRevisionLog').where('docId', '==', request.resource.data.docId).length;
}

Is there a way to query the collection like this in a security rule?

(Here's the Typescript class for the document, if that's helpful)

class DocumentManagerChange {
    docId : string;
    actorId : string;
    lastRevision : number;
    op: any;
}

Upvotes: 0

Views: 41

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

It's not possible to run a query in a security rule. You can only use get() to get a single document using its known path. If you need some sort of count in a rule, you will have to maintain that count in another known document, to be read at the time of the query.

Upvotes: 1

Related Questions