Search code examples
firebaseecmascript-6google-cloud-firestorees6-promise

Multi document creation in sub-collection in Firestore


I am trying to write a function that will:

  1. Create documents in a sub collection
  2. Allow for a then/catch call back after all sub documents have been created
    export const doCreateSubs = (Id, count) => {
        if (count > 0 && count <= 50){
            const times = n => f => {
              let iter = i => {
                if (i === n) return;
                f(i);
                iter(i + 1);
              };
              return iter(0);
            };
            times(count)(i => {
                db
                  .collection("parent")
                  .doc(`${Id}`)
                  .collection("sub")
                  .add({ 
                    subName: `name ${i + 1}`, 
                    dateCreated: new Date() 
                });
            });
        }
    }

I've played around with batch but it doesn't work with .collection. I know my function is really poor - is there a generally bettery way of doing this?


Solution

  • So i've just realised you can .doc() with no value and it will create a uid for the key. I can also return .commit and recieve a call back when it's complete!

    export const doCreateSubs = (Id, count) => {
        if (count > 0 && count <= 50){
    
            const times = n => f => {
              let iter = i => {
                if (i === n) return;
                f(i);
                iter(i + 1);
              };
              return iter(0);
            };
    
            const batch = db.batch();
    
            times(count)(i => {
    
                const ref = db
                  .collection("parent")
                  .doc(`${Id}`)
                  .collection("subs")
                  .doc();
    
                batch.set(ref, {
                    boxName: `Sub ${i + 1}`, 
                    dateCreated: new Date()
                });
    
            });
    
            return batch.commit();
        }
    }