How to save the documentID in a document in Firebase using Flutter

Viewed 3062

I have a collection called favoritePost in Firebase and that collection has several fields that get data from my app, one of the fields is the id that needs to be the documentID that is generated when the document is created, the issue is that I'm using too much code to achieve this result and I'm also getting an error for about 2 seconds when the document is being created.

I would like to know if there is a better implement this and how to fix the error.

Here I create the collection

The issue is here, when the collection is being created I get an error in my homepage because this document does not have data, it just creates the fields and I can't use docref.documentId inside the fields, so I have to create a new method that updates this collection and saves the data including the docref.documentId.

final docsref = await favRef
          .document(widget.currentUserId)
          .collection('favoritePost')
          .add(
        {
          'imageUrl': '',
          'caption': '',
          'likeCount': 0,
          'authorId': '',
          'timestamp': '',
          'userName': '',
          'userImage': '',
          'id': '',
          'idSecondPost': '',
          'experience': '',
          'cSrateStars': '',
          'productName': '',
          'brand': '',
          'cost': '',
          'envioDiasRateStars': '',
          'easyPurchaseRateStars': '',
          'totalRate': '',
          'businessName': '',
          'recomendation': '',
          'videoLink': '',
        },
      );

Here I pass some data including the docsref.documentID to my database file

DatabaseService.addFavorite(
          currentUserId: widget.currentUserId,
          post: widget.reviews,
          docref: docsref.documentID);

Here the data is saved into the collection created before, now I'm able to include the docsref.documentID into the id field

static void addFavorite(
      {String idReview,
      Reviews post,
      String currentUserId,
      String toId,
      String docref}) {
    DocumentReference postRef = reviewRef.document(post.idReview);
    postRef.get().then(
      (doc) {
        final docsref = favRef
            .document(currentUserId)
            .collection('favoritePost')
            .document(docref)
            .updateData({
          'imageUrl': post.imageUrl,
          'caption': post.comments,
          'likeCount': post.likeCount,
          'authorId': post.authorId,
          'timestamp': post.timestamp,
          'userName': post.userName,
          'userImage': post.userImage,
          'idReview': post.idReview,
          'experience': post.address,
          'cSrateStars': post.cSrateStars,
          'productName': post.productName,
          'brand': post.brand,
          'cost': post.cost,
          'envioDiasRateStars': post.envioDiasRateStars,
          'easyPurchaseRateStars': post.easyPurchaseRateStars,
          'totalRate': post.totalRate,
          'businessName': post.businessName,
          'recomendation': post.recomendation,
          'id': docref,
          'videoLink': post.videoLink,
        });
      },
    );
  }
2 Answers

You can generate the documentID in the homepage by doing the following:

var randomDoc = await favRef
          .document(widget.currentUserId)
          .collection('favoritePost')
          .document();

By using document() without a path, it will generate a document id for you, and then you can do:

final docsref = await favRef
          .document(widget.currentUserId)
          .collection('favoritePost')
          .document(randomDoc.documentID)
          .setData(
        {
          'imageUrl': '',
          'caption': '',
          'likeCount': 0,
          'authorId': '',
          'timestamp': '',
          'userName': '',
          'userImage': '',
          'id': '',
          'idSecondPost': '',
          'experience': '',
          'cSrateStars': '',
          'productName': '',
          'brand': '',
          'cost': '',
          'envioDiasRateStars': '',
          'easyPurchaseRateStars': '',
          'totalRate': '',
          'businessName': '',
          'recomendation': '',
          'videoLink': '',
          'docId' : randomDoc.documentID
        },
      );

This way you generate the id immediately in the homepage and add it to the docId field without needing to update.

String collectionRef= 'collectionRef';
String docId = Firestore.instance
    .collection(collectionRef)
    .document()
    .documentID;
var docRef = Firestore.instance
    .collection(collectionRef)
    .document(docId);

Then setData to docRef including documentId: docId

Related