Paul Kruger
Paul Kruger

Reputation: 2304

Firestore: how do I add a document and a subcollection document

In Flutter Firestore I do this to add a document:

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

But how do I add a document AND add a document in a subcollection as well, I need something like this:

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

(in this case, I want the user who created the group to be the first member, and an admin as well)

Upvotes: 1

Views: 752

Answers (1)

danh
danh

Reputation: 62676

That first add returns a "future" that resolves to the doc reference of the new doc. You can use that value by "await"-ing for it...

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

Edit

To handle in a single http request, you might try a write batch.

Paul Edit:

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

Upvotes: 2

Related Questions