Flutter & Firebase : How can I put the documentID into the document field the moment I just create the document?

Viewed 829

Flutter & Firebase : How can I put the documentID into the document field the moment I just create the document?

Normally, if we create the document without specifying the documentID, firebase will generate an ID for us, right?

In my case, I want firebase to generate the ID for me and then put that id into one of the document field. How do I do that?

await feedbackCollection.document().setData({
      'comment' : comment,
      'feedback_id' : ????,
    });
3 Answers
DocumentReference docRef = await feedbackCollection.document();
    docRef.setData({
      'comment' : comment,
      'feedback_id' : docRef.id,
    });

You can do the following:

final firestoreInstance = Firestore.instance;
var docId = firestoreInstance.collection("feedback").document();

await firestoreInstance.collection("feedback").document(docId).setData({
      'comment' : comment,
      'feedback_id' : docId,
    });

Using document() it will generate a random id, which you can then assign to a variable and use it in the field when creating the document.

RaisedButton(
            child: Text('Click Here'),
            onPressed: () async {
              await FirebaseFirestore.instance
                  .collection('xCollection')
                  .add({'comment': 'comment1'}).then(
                      (DocumentReference docRef) =>
                          docRef.update({'documentID': docRef.id}));
            },
          ),

This way you will be able to create a document with Firebase generated ID inside xCollection (you can change the collection name) and once the document is created with the required fields it will update the document adding one more field called 'documentID' and add it's ID to that field.

Related