【问题标题】:How to add 2 collections in Firestore using React Native?如何使用 React Native 在 Firestore 中添加 2 个集合?
【发布时间】:2019-02-07 08:12:43
【问题描述】:

我想在 React Native 的 Firestore 中添加 2 个集合。 像JOIN可以用来添加2个表。 Firestore 中的JOIN 是否有其他选择来添加集合?

我想添加这 2 个集合 usersusers_2 我怎样才能做到这一点?请帮忙

【问题讨论】:

    标签: firebase react-native google-cloud-firestore


    【解决方案1】:

    在撰写本文时,无法在 Firestore 中跨集合查询文档(这显然是路线图中的一项功能,但请参阅此最近的博客文章 https://cloud.google.com/blog/products/databases/announcing-cloud-firestore-general-availability-and-updates - 请参阅要点“即将推出更多功能” -)。

    这意味着您必须发出两个查询(每个表一个查询,发送到get all the collection docs)并在前端连接/组合它们的结果。

    另一种方法是复制您的数据(这在 NoSQL 世界中很常见)并创建包含所有文档副本的第三个集合。

    对于最后一种方法,您可以使用 Batched Write 如下(在 Javascript 中):

    // Get a new write batch
    var batch = db.batch();
    
    var docData = {email: 'test@gmail.com', fullname: 'John Doe'}
    
    // Set the value of doc in users collection
    var usersRef = db.collection('users').doc();
    batch.set(usersRef, docData);
    
    // Set the value of doc in the allUsers collection (i.e. the third collection)
    var allUsersRef = db.collection('allUsers').doc();
    batch.set(allUsersRef, docData);
    
    // Commit the batch
    return batch.commit().then(function () {
      // ...
    });
    

    【讨论】:

    • 谢谢。另外,您能告诉我如何在 Firestore 中创建数据副本吗?
    • 有几种可能: 1/当您使用批量写入写入usersusers_2集合时,您可以从前端写入第三个集合(firebase.google.com/docs/firestore/manage-data/…) . 2/ 每次您在两个“主要”usersusers_2 集合 (firebase.google.com/docs/functions/firestore-events?authuser=0) 之一中创建文档时,您可以使用云函数在第三个集合中创建文档副本。这取决于您的确切需求和应用架构...
    • @ShubhamBisht 我刚刚添加了一个批处理写入的示例
    • 谢谢 Renaud Tarnec
    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多