【问题标题】:How to add multiple docs to a collection in firebase?如何将多个文档添加到firebase中的集合?
【发布时间】:2019-06-16 17:49:48
【问题描述】:

我正在使用 React native 和 react-native-firebase

我的目标是一次将多个文档(对象)添加到集合中。 目前,我有这个:

const array = [
  {
     name: 'a'
  },{
    name: 'b'
  }
]
array.forEach((doc) => {
  firebase.firestore().collection('col').add(doc);
}

这会在对集合进行的每次更新时触发其他设备上的更新。 如何将这些文档批量处理一次更新?

【问题讨论】:

    标签: reactjs firebase react-native


    【解决方案1】:

    你可以像这样创建批量写入

    var db = firebase.firestore();
    var batch = db.batch()
    

    在你的数组中添加更新

    array.forEach((doc) => {
      var docRef = db.collection("col").doc(); //automatically generate unique id
      batch.set(docRef, doc);
    });
    

    最后你必须提交那个

    batch.commit()
    

    【讨论】:

    • 您是否能够在与提交相同的调用中获得生成的唯一 ID?我想我必须通过调用另一个 get 方法来检索它..
    • 如何为文档使用自定义 ID?
    • @rbansal 就设置好了。接受字符串的文档方法
    【解决方案2】:

    您可以将多个写入操作作为一个批处理执行,其中包含 set()、update() 或 delete() 操作的任意组合。一批写入原子完成,可以写入多个文档。

    var db = firebase.firestore();
    var batch = db.batch();
    
    array.forEach((doc) => {
    
      batch.set(db.collection('col').doc(), doc);
    }
    // Commit the batch
    batch.commit().then(function () {
        // ...
    });
    

    【讨论】:

    • 太棒了!谢谢
    • 这被认为是单次写入的成本还是数组元素的数量?
    【解决方案3】:

    来自数据库的批处理还有一个创建函数,可以在集合中添加一个新文档,如果已经有一个文档,则会引发错误。我们只需要对文档的引用。请注意,此功能存在于 firebase 的 admin sdk 中。

    const batch = db.batch();
    await users.map(async (item)=> {
        const collectionRef = await db.collection(COLLECTION_NAME).doc();
        batch.create(collectionRef, item);
      });
    
    const result = await batch.commit();
    
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 2019-06-04
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多