【问题标题】:AngularFire2 (firestore) Need to set multiple docs at once like RealTime DatabaseAngularFire2(firestore)需要像实时数据库一样一次设置多个文档
【发布时间】:2018-04-30 19:08:09
【问题描述】:

我正在从 Firebases 实时数据库切换到 Firestore。并且在如何添加数据上有一点区别

我的数据

我有一个产品对象

const productsObj {
    products : [ {...},{...},{...},{...} ]
    meta: {}
}

火力基地

我的预期结构是......

收藏productsObj{}

文档productsObj.products(多个)

字段productsObj.products[i].name

我的尝试

this.productCollection = this.afs.collection('products'); // compared to productsObj

this.productCollection.add(productsObj); // adds all products as one doc
this.productCollection.add(productsObj.products); // cant add array
this.productCollection.add(productsObj.products[0]); // works

最后一个有效,但对吗?我将不得不遍历几个对象并为每个新文档调用 firebase。

一次将所有productsObj.products 添加为文档的最佳方法是什么?

编辑 productCollection 是这样声明的 productCollection: AngularFirestoreCollection<any>;

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    当您add() 到集合时,您正在为每次调用创建一个文档。

    你想要这样的东西:

    productsObj.products.forEach( (project) => {
      this.productCollection.add(product);
    };
    

    AngularFire2 documentation on Adding Documents to a Collection

    【讨论】:

    • 我明白了。我想知道为列表中的每个项目发布帖子是否是一种好习惯。因为物品很多。在实时数据库中,我们能够一次添加大的 json 负载。
    • 如果您需要查询产品,每个产品都需要是集合中的一个文档,因为查询仅适用于集合。 structuring data in Firestore 有很好的指导。每个文档限制为 1MB,因此即使您不需要查询,将大量产品存储在一个文档中也可能不切实际。您可以使用Transaction or Batched Write 可靠地创建所有文档。
    • 你想明白了。我有很多来自另一个数据库的项目。我需要它们都是单独的文档。我正在寻找一种 Firebase 方法,我可以一次将它们全部添加,而不是“foreach item add doc one at time”
    • 很简单,我需要add multiple documents at once 就像标题说的那样
    • Firestore 中没有可用的导入/导出功能,就像 RTDB 中一样。请参阅:How to import data to Cloud Firestore? 以获取一个简单的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多