Home > OS >  Flutter : check if there's specific data in the subcollection
Flutter : check if there's specific data in the subcollection

Time:11-22

I'm creating a post that uploads data to Firestore's sub-collection and brings it up to MyBookmark page. It's good to create a sub-collection and upload data simply. And now I'd like to add a 'data duplication prevention' function here. If the post is already saved in the bookmark, should not upload it.

For this purpose, I would like to check if the post is already in the collection when I press the bookmark button.

        IconButton(
          onPressed: () async {
            //get userModel
            UserModelState _userModelstate =
                Provider.of<UserModelState>(context, listen: false);

            //=========================================
            //duplication data test
            DocumentReference bookmarkRef = Firestore.instance
                .collection(COLLECTION_USERS)
                .document(_userModelstate.userModel.userKey)
                .collection(COLLECTION_BOOKMARk)
                // .where(KEY_BOOKMARK_PRODUCTKEY, isEqualTo: productKey)
                .document();

            DocumentSnapshot bookmarkSnapshot = await bookmarkRef.get();

            //test (return "No exist")
            if(bookmarkSnapshot.exists) {
              print("Yes exist");
            } else {
              print("No exist");
            }

enter image description here

I tried writing a code to check if there was data in the collection, but it is always printed as "No exist".
How can I confirm the existence of a specific document in collection?

Thank you.

CodePudding user response:

If the productKey is supposed to be unique in the Bookmark collection of the user, consider using the productKey as the document ID. Since document IDs are by definition unique within their collection, using them guarantees unique product keys without you having to write any code for it.


That said, you current code can't work because you call document(). Whenever you call document() without any parameters, it generates a reference to a new unique document. And since you immediately call get() on that reference, the document will (also: by definition) not exist yet.

To check if a document with a specific product ID exist, you will need to run a query:

CollectionReference bookmarksRef = Firestore.instance
    .collection(COLLECTION_USERS)
    .document(_userModelstate.userModel.userKey)
    .collection(COLLECTION_BOOKMARk);
Query bookmarkQuery = bookmarksRef.where(KEY_BOOKMARK_PRODUCTKEY, isEqualTo: productKey);

QuerySnapshot bookmarkSnapshot = await bookmarkQuery.get();

if (bookmarkSnapshot.size > 0) {
  print("product key already in use");
}
  • Related