简体   繁体   中英

How to get cloud firestore document unique Id before adding data to cloud firestore as Realtime database

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM