Firebase Firestore: Is there a way to enforce requ

2020-04-17 05:11发布

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?

2条回答
我只想做你的唯一
2楼-- · 2020-04-17 05:40

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 and field3, you could use hasAll:

allow write: if resource.data.keys().hasAll(['editor', 'admin']);
查看更多
Explosion°爆炸
3楼-- · 2020-04-17 05:45

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:

const functions = require('firebase-functions');

exports.setDefaultValueFirestore = functions.firestore.document('defaultDemo/{someDoc}')
    .onCreate(async (snap, context) => {
      if(!('defaultWanted' in snap.data())) {
        return snap.ref.set({
          'defaultWanted': 'my default value'
        }, {merge: true});  
      } else {
        return Promise.resolve();
      }
    });

This will set the defaultWanted field on any document created in /defaultDemo to my 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.

查看更多
登录 后发表回答