0

I have created a database in firestore and loaded the test data successfully. But later I noticed that some data is missing in database. I found that when I load the same records with a different value for some fields the old record is replaced with the new record. I feel like this is the issue in the database design. I need to collect and save all the records even if it is a duplicate records at entire records level.

Could you please let me know how to do this ?

private void exportToFireStore() {
    // Access a Cloud Firestore instance from your Activity
    final FirebaseFirestore db = FirebaseFirestore.getInstance();

    /*  ----------------_-------Collection delete is not supported-----------------------
        ----------Hence get all the document (coins) for individual Docs delete----------
    */

    //-------------------------------  Getting document (coins) Ends  ---------------------------------------------
    final List<String> coinsFromFirestore = new ArrayList<>();

    db.collection("cryptos").document(userEmailID).collection("coin")
            .whereEqualTo("createdBy", userEmailID)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            System.out.println("Testing 1 Batch Read done" + document.getData());
                            coinsFromFirestore.add(document.getData().get("coinname").toString());
                        }

                        //-------------------------------  Getting document (coins) Ends  ---------------------------------------------


                        if(coinsFromFirestore.size()>0){

                            for (int i=0;i<coinsFromFirestore.size();i++) {

                                if ( i<(coinsFromFirestore.size()-1) ) {
                                    db.collection("cryptos").document(userEmailID).collection("coin").document(coinsFromFirestore.get(i))
                                            .delete()
                                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                                @Override
                                                public void onSuccess(Void aVoid) {
                                                    System.out.println("Testing 1 Successfully Deleted the document "  );
                                                }
                                            })
                                            .addOnFailureListener(new OnFailureListener() {
                                                @Override
                                                public void onFailure(@NonNull Exception e) {
                                                    System.out.println("Testing 1 Error Deleting the document ");
                                                }
                                            });
                                }else{  
                                    db.collection("cryptos").document(userEmailID).collection("coin").document(coinsFromFirestore.get(i))
                                            .delete()
                                            .addOnSuccessListener(new OnSuccessListener<Void>() {
                                                @Override
                                                public void onSuccess(Void aVoid) {
                                                    addTranToFireBaseeNow(db);
                                                }
                                            })
                                            .addOnFailureListener(new OnFailureListener() {
                                                @Override
                                                public void onFailure(@NonNull Exception e) { 
                                                }
                                            });
                                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! For last coin Ends  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                                }
                            }
                        }else{
                            addTranToFireBaseeNow(db);
                        }

                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
    //-------------------------------  Getting document (coins) Ends  ---------------------------------------------


}

private void addTranToFireBaseeNow(FirebaseFirestore db) {
    WriteBatch batch = db.batch();
    DocumentReference newCoinRef;
    //CollectionReference cryptos = db.collection("cryptos");
    List<Tran> tranList = getAllTranForFireStore();

    String firebaseUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
    for (Tran t : tranList) { 
        Map<String, Object> tranData = new HashMap<>();
        tranData.put("firebaseid", firebaseUID);
        tranData.put("createdBy", userEmailID);
        tranData.put("coinid", t.getCoinID());
        tranData.put("coinname", t.getCoinName());
        tranData.put("coinsymbol", t.getCoinSymbol());
        tranData.put("date", String.valueOf(t.getDate()));
        tranData.put("qty", String.valueOf(t.getQty()));
        tranData.put("price", String.valueOf(t.getPrice()));
        tranData.put("priceunit", String.valueOf(t.getPriceUnit()));
        newCoinRef= db.collection("cryptos").document(userEmailID).collection("coin").document(t.getCoinName());
        batch.set(newCoinRef, tranData);
    }
    batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            // ... 
        }
    });
}

enter image description here

No index is setup for my DB

enter image description here

iappmaker
  • 2,945
  • 9
  • 35
  • 76

2 Answers2

0

Since you are using set without any options, it will overwrite the existing data. But your requirement is to merge your data, so you have to use the merge option as follows:

batch.set(newCoinRef, tranData, SetOptions.merge());

You can read more about options here.

Furthermore there is a good post which lists the differences between set, update and create.

kAliert
  • 768
  • 9
  • 21
0

You can use update and change one variable

 reference.document("documentname").update("field", variable)

or

 reference.document("documentname").set({
    field: variable
}, { merge: true });

Or.. if you have to update an entire object, you can use:

 reference.document("documentname").set(newObject, { merge: true });

Check this article: https://saveyourtime.medium.com/firebase-cloud-firestore-add-set-update-delete-get-data-6da566513b1b