I am manually adding data for an app I am creating. I have to add many documents to a collection, all of which have to contain the same 5 fields. Is there a way to automatically create these fields when I create a new document in the Firebase console? And to also enforce all documents have those 5 fields (so that I don't make mistakes) ?
Additionally, is there a better way to manually adding this data than from the Firebase console? Through JSON for example?
There are two separate questions here. Both have been answered before, but never in a single question, so I'll do that here.
Can you set default values for new documents in a collection?
This is not possible. You will have explicitly write those values into each new document you create.
Can you enforce that new documents in a collection have values for certain fields?
This is possible through the use of Firebase's server-side security rules.
For example, to ensure a document has values for
field1
,field2
andfield3
, you could usehasAll
:One option for setting default values on documents is to implement a cloud function with an onCreate trigger, which will then look at each new document when it is created and add the default value if it does not exist. Note that this isn't perfect, as there will be some non zero time between when the object is created and when the function runs, but it may be sufficient for some cases.
Here's what one such function might look like:
This will set the
defaultWanted
field on any document created in/defaultDemo
tomy default value
.However, it is likely more stable to use the security rules and have the client always supply the needed fields as @Frank suggests if you can.