如何在firestore中获取setData的ID?

Pri*_*nou 3 database firebase firebase-realtime-database flutter google-cloud-firestore

我正在编写一个 flutter 应用程序,在其中我在 firebase 中设置了一个文档实例,如下所示:

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

然后我想获取上述文档 ID 并执行以下操作:

  _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
Run Code Online (Sandbox Code Playgroud)

所以我的问题是有没有办法获取第一个文档的 id 并将其用作第二个查询的参考?

cre*_*not 6

为了简化document().setData(data)add(data)在我的解决方案中使用的,它完全相同并返回DocumentReferencefrom 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
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用返回的DocumentReference(如上所述)并使用documentIDgetter从您新创建的文档中提取 ID。