hanjustin
hanjustin

Reputation: 169

How to update only certain fields from data through database rule?

My database:

{ "user" :
    "$userID": {
        "name" : "Anon",
        "age" : 99
    }
}

If client accidentally sends incorrect data but with some valid data, is there a way to update the server only with the valid data?

For example,

user1.updateChildValues(["name" : "John Snow", "age" : 30, "BADKEY" : "BAD DATA"])

I want the above update attempt to work, but only update the database with ["name" : "John Snow", "age" : 30] in the above situation using database security rule. Is there a way to do this?

Upvotes: 0

Views: 889

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

It sounds like you want to enforce a schema on your data structure. You can do this in your security rules, by validating the properties (and rejecting unmatched properties):

{ "user" :
    "$userID": {
        ".validate": "newData.hasChildren('name', 'age')",
        "name": {
            ".validate": "newData.isString()"
        },
        "age" : {
            ".validate": "newData.isNumber()"
        },
        "$other": {
            ".validate": false
        }
    }
}

The $other rule here matches any children that are not matched by the more explicit rules, and then rejects them.

Upvotes: 1

Related Questions