Home > Software engineering >  How to get cloud firestore document unique Id before adding data to cloud firestore as Realtime data
How to get cloud firestore document unique Id before adding data to cloud firestore as Realtime data

Time:10-10

We can get pushed Key in realtime database before adding data but in cloud firestore I could not find any method to find unique key before adding data.

String uniqueKey = ref.push().getKey();

So I am doing two operation add and then update .If I can get unique key before adding data to firestore I can do it one operation just add with unique key included in the document.

Currently I am doing like this.

Collection Reference

final sitesRef = FirebaseFirestore.instance
      .collection('book_mark')
      .doc(getUserId())
      .collection("link")
      .withConverter<SiteModel>(
        fromFirestore: (snapshots, _) => SiteModel.fromJson(snapshots.data()!),
        toFirestore: (siteModel, _) => siteModel.toJson(),
      );

Add document then get document Id from response then update the document with document Id.So if update operation is failed somehow I could not access the document anymore. So it will create a problem down the line.

Future<String> addSiteFireStore(SiteModel siteModel) async {
    try {
      DocumentReference<SiteModel> response = await sitesRef.add(siteModel);
      final Map<String, dynamic> data = <String, dynamic>{};
      data['docId'] = response.id;
      sitesRef.doc(response.id).update(data);
      _logger.fine("Link added successfully");
      return "Link added successfully";
    } on Exception catch (_) {
      _logger.shout("Could not add link.Please try again");
      return "Could not add link.Please try again";
    }
  }

Is there any way to get the document Id beforehand? Thanks in advance.

CodePudding user response:

You can get a new document reference without writing to it by calling doc() (without arguments) on a CollectionReference. Then you can get the id property from the new document reference, similar to how you call getKey() on the new RTDB reference.

So:

final newRef = FirebaseFirestore.instance
      .collection('book_mark')
      .doc();
final newId = newRef.id;

Also see the FlutterFire documentation on CollectionReference.doc().

  • Related