Search code examples
javascriptfirebasegoogle-cloud-firestorefirebase-security

Check that a newly added field in firestore document conforms to structure


I have a document in firestore consisting of a series of maps. Thier field names are random uuids:

-6e219b89-98fb-44cd-b6ad-e22888b6fb2f
 -name: 'Harry'
 -age: 20 

-345c635a-11cb-4165-86ef-50be50794532
 -name: 'Mary'
 -age: 30

I have a piece of client code which adds a new map to this document.

await updateDoc(docRef, {
    [crypto.randomUUID()]: {
            name: 'Sally',
            age: 24,
    }
});

How can I check that the newly submitted field is a map with name=string and age=number?

If I knew the field name I could write the security rule

request.resource.data.name is string;

But in this case I don't know the value of the random UUID which is the new field in the document.


Solution

  • Firestore security rules cannot iterate over fields (or anything else). They must always know exactly what field to check. This means that with your current write operation, there is no way for the rules to know what field to check.

    A simple workaround is to also write the crypto.randomUUID() value in a known location, e.g. newField:

    const uuid = crypto.randomUUID()
    await updateDoc(docRef, {
        newField: uuid,
        [uuid]: {
                name: 'Sally',
                age: 24,
        }
    });
    

    Now your rules can read newField to determine what field was added, and then use that value to check whether the new field adheres to your rules.

    Also see: