How to get the Id of of setData in firestore?

2,627

To simplify document().setData(data) I used add(data) in my solution, which does exactly the same and returns the DocumentReference from document().

// insert your data ({ 'group_name'...) instead of `data` here
final DocumentReference documentReference = 
  await _firestoreInstance.collection("groups").add(data);

final String groupID = documentReference.documentID;

// groupID contains the documentID you were asking for
// here I am just inserting it into your example code from the question
_firestoreInstance.collection("colleges").document(collegeStudent.collegeId)
  .collection('activeGroups')
  .add({'group_id': groupID}); // using add instead of `document().setData` here as well

As you can see I am making use of the returned DocumentReference (as explained above) and using the documentID getter to extract the ID from your newly created document.

Share:
2,627
Prince Hodonou
Author by

Prince Hodonou

Updated on December 06, 2022

Comments

  • Prince Hodonou
    Prince Hodonou over 1 year

    I'm writing a flutter app in which I set an instance of a document in firebase like this:

    await _firestoreInstance.collection("groups").document().setData(
    {
      'group_name': groupName,
      'class_name': className,
      'location': groupLocation,
      'time': groupTime,
      'date': groupDate,
      'number_in_group': 1
    },);
    

    Then I want to take the above document id and do something like this:

      _firestoreInstance.collection("colleges").document(collegeStudent.collegeId).collection('activeGroups').document().setData({'group_id':*above document id goes here*}); //above document id is the id of the document created by the first query
    

    So my question is there a way I can get the id of the first document and use it as a reference for the second query?