Reputation: 117
I am adding a new document to my firestore group 1, and use the new documentID of that group to update two other documents. Afterwards, I'd like to save the documentID from group 1 in a variable in order to pass it to my widgets.
How can I receive and save the documentID when adding a new document to group 1 without causing an extra firestore read? I don't understand why the code below works except for
valueId = value.documentID
Thanks
onPressed: () {
firestore.collection('Gruppe').add({
'Group': messageTextController.text.trim(),
'Gruppenersteller': loggedInUser.uid,
'Gruppenmitglieder': FieldValue.arrayUnion([
loggedInUser.email,
widget.userEmail,
]),
'Angelegt': FieldValue.serverTimestamp(),
}).then((value) => {
firestore
.collection('Nutzer')
.document(loggedInUser.uid)
.updateData({
'Slates': FieldValue.arrayUnion([value.documentID])
}),
firestore
.collection('Nutzer')
.document(widget.userNutzerId)
.updateData({
'Slates': FieldValue.arrayUnion([value.documentID])
}),
valueId = value.documentID,
});
print('valueID');
print(valueId);
Upvotes: 1
Views: 58
Reputation: 317392
You can get the random ID of a document before it's added like this:
val docRef = firestore.collection('Gruppe').doc()
val docId = docRef.documentID;
Then you can go on and create the document with set()
:
docRef.set(...)
In your code above, I would expect that print(valueId)
to not print the assigned value of value.documentID
, because add()
and then()
are asynchronous and return immediately with a Future. In fact, any function that returns a Future will do so immediately. The callback you provide to then()
will be invoked some time later, after the operation is complete. So, effectively, your code is trying to print the document ID before it's been assigned. That's why I'm suggesting that you get it immediately of the reference instead of trying to get it later.
Upvotes: 2