在Firestore中的子集合中创建多文档

时间:2018-04-06 20:44:15

标签: firebase ecmascript-6 google-cloud-firestore es6-promise

我正在尝试编写一个函数:

  1. 在子集合中创建文档
  2. 在创建所有子文档后允许进行then / catch回调

    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:姓名$ {i + 1} , dateCreated: new Date() }); }); } }

  3. 我已批量播放,但它不能与.collection一起使用。我知道我的功能真的很差 - 这种做法通常是一种很好的方法吗?

1 个答案:

答案 0 :(得分:1)

所以我刚刚意识到你可以.doc()没有任何价值,它会为密钥创建一个uid。我还可以返回.commit并在完成后接听回电!

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();
    }
}