How do I write a new record to Firebase and use its doc ID as a field all within the same operation?

Viewed 23

I know I can add a document using the code below and that I can also update a document after adding it, but how do I write a new document's own ID into one of the fields of that same document?

Future<void> addUser() {
      // Call the user's CollectionReference to add a new user
      return users
          .add({
            'full_name': fullName, // John Doe
            'company': company, // Stokes and Sons
            'age': age // 42
          })
          .then((value) => print("User Added"))
          .catchError((error) => print("Failed to add user: $error"));
    }

For example, I want to add a new record and let Firebase auto-generate the doc ID. Let's say it generates ABC123. In the same write, I want to both generate this document ABC123 and put this value into one of the fields called groupID. I'd like to avoid doing a write then an update to save on the Firebase costs.

0 Answers
Related