For example, if I have a Firestore document that looks like this:
{
threadId: 'abc',
authorId: 'abc',
content: 'blah blah blahh'
}
Can I make Firebase throw an error from the server if I accidentally write some code that adds another field, like this:
{
ACCIDENT: 'OOPS! THIS FIELD SHOULD NOT BE HERE',
threadId: 'abc',
authorId: 'abc',
content: 'blah blah blahh'
}
Like static typing for the shape of each document and enforced from the Firestore server. Is that possible?
CodePudding user response:
A possible solution would be to create a Cloud Function, that reads the content of your document once it is updated. So for example, if your document has a fixed number of fields, then you should always check against that number, in your example, it would be three. If for example, the result of the check would be four, then you can take some actions.
Another approach would be to check the existence of a field in a document, before updating it. If that particular field exists, do the update, otherwise, throw an error.
CodePudding user response:
If you write the data from a client-side SDK, you can use security rules to validate the data. For some examples of this, see the Firestore documentation on validating data in security rules.
For example, to test that the document has only the three fields you mention, you could do:
allow write: if request.resource.data.keys.hasOnly("threadId", "authorId", "content")