【问题标题】:Firestore: how do I add a document and a subcollection documentFirestore:如何添加文档和子集合文档
【发布时间】:2019-07-09 15:10:06
【问题描述】:

在 Flutter Firestore 中,我这样做是为了添加一个文档:

Firestore.instance
    .collection('groups').add({'name': 'Group Name 1'});

但是如何添加文档并在子集合中添加文档,我需要这样的东西:

Firestore.instance
    .collection('groups').add({'name': 'Group Name 1'})
    .collection('members').add({'name': 'newMemberName', 'isAdmin': true});

(在这种情况下,我希望创建组的用户成为第一个成员,同时也是管理员)

【问题讨论】:

    标签: firebase flutter google-cloud-firestore crud


    【解决方案1】:

    第一个add 返回一个“未来”,它解析为新文档的文档引用。您可以通过“等待”来使用该值...

    var docRef = await Firestore.instance.collection('groups').add({'name': 'Group Name 1'});
    docRef.collection('members').add({'name': 'newMemberName', 'isAdmin': true});
    

    编辑

    要处理单个 http 请求,您可以尝试写入批处理。

    保罗编辑:

          // Add new group to database
          var batch = Firestore.instance.batch();
    
          // Create the group
          var newGroup = Firestore.instance.collection('groups').document();
          batch.setData(newGroup, {'name': value});
    
          // Create the new members subcollection
          var newMember = newGroup.collection('members').document();
          batch.setData(newMember, {
            'users_documentId': currentUser.documentId,
            'users_displayName': currentUser.displayName,
            'isAdmin': true
          });
    
          // Commit the batch edits
          batch.commit().catchError((err) {
            print(err);
          });
    

    【讨论】:

    • 谢谢,问题解决了。但是有没有办法用一个“http调用”来做到这一点
    • @PaulKruger,我从来没有在 dart 中做过,但是(也许??)另一种方法是批量写入。这是一个 JS 参考...firebase.google.com/docs/reference/js/…
    • 谢谢你!这至少应该让我朝着正确的方向前进:)
    • 很高兴为您提供帮助。编辑建议——不是很有信心——写批处理方法
    • 老兄,谢谢!我的下一个堆栈问题将是“如何批量编辑”,但是感谢您的代码,我想通了!我在您的答案中添加了正确的代码。只需删除您的东西并改用我的东西...非常非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2018-07-22
    • 1970-01-01
    相关资源
    最近更新 更多