JustLearningAgain
JustLearningAgain

Reputation: 2287

How do you get the document id after adding document in Cloud Firestore in Dart

Im using the following code to update a Cloud Firestore collection using Dart/Flutter.

  final docRef = Firestore.instance.collection('gameLevels');
  docRef.document().setData(map).then((doc) {
    print('hop');
  }).catchError((error) {
    print(error);
  });

I'm trying to get the documentID created when I add the document to the collection but the (doc) parameter comes back as null. I thought it was supposed to be a documentReference?

Since it's null, I obviously can't use doc.documentID.

What am I doing wrong?

Upvotes: 11

Views: 20105

Answers (5)

Bill Nice
Bill Nice

Reputation: 100

This worked for me

  //add a passed employee to firebase collection called employees

  static Future<void> addEmployee(Employee employee) async {
    final CollectionReference employees = FirebaseFirestore.instance.collection('employees');

    var doc = employees.doc();
    employee.employeeID = doc.id;
    await doc.set(employee.toJson());
 }

Upvotes: 0

ShadeToD
ShadeToD

Reputation: 490

@Doug Stevenson was right and calling doc() method will return you document ID. (I am using cloud_firestore 1.0.3)

To create document you just simply call doc(). For example I want to get message ID before sending it to the firestore.

  final document = FirebaseFirestore.instance
      .collection('rooms')
      .doc(roomId)
      .collection('messages')
      .doc();

I can print and see document's id.

print(document.id)

To save it instead of calling add() method, we have to use set().

  await document.set({
    'id': document.id,
    'user': 'test user',
    'text': "test message",
    'timestamp': FieldValue.serverTimestamp(),
  });

Upvotes: 7

Rahul Kushwaha
Rahul Kushwaha

Reputation: 6722

Using value.id ,You can fetch documentId after adding to FireStore .

CollectionReference users = FirebaseFirestore.instance.collection('candidates');
  

      Future<void> registerUser() {
     // Call the user's CollectionReference to add a new user
         return users.add({
          'name': enteredTextName, // John Doe
          'email': enteredTextEmail, // Stokes and Sons
          'profile': dropdownValue ,//
          'date': selectedDate.toLocal().toString() ,//// 42
        })
            .then((value) =>(showDialogNew(value.id)))
            .catchError((error) => print("Failed to add user: $error"));
      }

Upvotes: 5

Ganapat
Ganapat

Reputation: 7488

You can try the following:

DocumentReference docRef = await 
Firestore.instance.collection('gameLevels').add(map);
print(docRef.documentID);

Since add() method creates new document and autogenerates id, you don't have to explicitly call document() method

Or if you want to use "then" callback try the following:

  final collRef = Firestore.instance.collection('gameLevels');
  DocumentReferance docReference = collRef.document();

  docReferance.setData(map).then((doc) {
    print('hop ${docReferance.documentID}');
  }).catchError((error) {
    print(error);
  });

Upvotes: 25

Doug Stevenson
Doug Stevenson

Reputation: 317467

If the Dart APIs are anything like other platforms, the document() method should return a document reference that has an id property with the randomly generated id for the document that's about to be added to the collection.

Upvotes: 1

Related Questions