有什么方法可以确保没有重复的项目被添加到 firestore 中,我正在使用 Flutter 和 Firebase,我对此很陌生

Is there any way to make sure no duplicate items get added in firestore, I'm using Flutter and Firebase and I'm pretty new to this

   Future addCart() async{
     final FirebaseAuth _auth = FirebaseAuth.instance;
     var currentUser = _auth.currentUser;
     CollectionReference _collectionRef = FirebaseFirestore.instance.collection("users-cart- 
     items");
    return _collectionRef.doc(currentUser!.email).collection("items").doc().set(
      {
       "name": widget.name,
        "price": widget.price,
        "images": widget.image,
      }).then((value) => print("Added To Cart"));

     }

我正在使用 collectionReference,它没有任何 .contain 方法来检查是否已经存在相同类型的项目。

I'm using collectionReference and it does not have any .contain method to check if there are items of the same type already existing

如您所见,没有任何方法可以帮助您仅在新文档不存在时添加它。所以你必须自己检查一下。这意味着在执行所需的写操作之前,您必须检查该对象(文档)是否存在。如果不存在,则执行写操作,否则,告知用户存在。