Karthic Srinivasan
Karthic Srinivasan

Reputation: 525

Query Firestore data and add one field to all the documents that match the query

I am building an Android app to sell books. My users can post ads for their used books and sell them. I am planning to add a feature where my users can opt to go anonymous. There will be checkbox with name Make me anonymous. If users check that box, their phone number and name will not be visible to others. Only a generic name should be visible.

Now the problem is, I want to put an entry anonymous = true in every ad documents that the user uploaded.

I want to query the ads that the user put and add a field anonymous = true. I want to do something like below:

 final CheckBox anonymousCB = findViewById(R.id.anonymousCB);
    anonymousCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (anonymousCB.isChecked()){
                WriteBatch batch = firestore.batch();
                DocumentReference sfRef = firestore.collection("books").whereEqualTo(uid,uid);
                batch.update(sfRef, "anonymous", "true");
            }
        }
    });

But I cannot make a query and insert a field into all the documents that match the query. Is there any better way to do this?

Upvotes: 0

Views: 476

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Is there any better way to do this?

Yes, there is. To solve this, please use the following lines of code inside onCheckedChanged() method:

Query sfRef = firestore.collection("books").whereEqualTo(uid, uid);
sfRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<String> list = new ArrayList<>();
            for (DocumentSnapshot document : task.getResult()) {
                list.add(document.getId());
            }

            for (String id : list) {
                firestore.collection("books").document(id).update("anonymous", true).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "anonymous field successfully updated!");
                    }
                });
            }
        }
    }
});

The result of this code would be to add the anonymous property to all your book objects and set it to true. Please note, I have used the boolean true and not the String true as you have used in your code. Is more convenient to be used in this way.

P.S. If you are using a model class for your books, please also see my answer from this post.

Upvotes: 2

Related Questions