In my App a user can have many different gymplans. So I have a collection where every gymplan has his own document. When creating a new plan I want to store the document id inside the document so that I have access to this document with the id.
When creating a new document firestore automatically create a unique id which is fine. But how can I get this id inside my code? So far my code to create a new plan looks like this:
Future createPlan(String planName, List exerciseNames, List rows) async {
return await usersCol.doc(myUser.uid).collection('plans').add({
'planId': /// here i want to save the document id firestore creates
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});
}
CodePudding user response:
You'd have to create the document first. Then use set()
instead of add()
. So:
final ref = usersCol.doc(myUser.uid).collection('plans').doc();
return await ref.set({
'planId': ref.id,
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});