AmanSharma
AmanSharma

Reputation: 841

Updating object nested inside Array in Firestore

I have a document which contains an array of object. The document is meant to store relations between two individuals on the app. They key defining the relation is status. example one document is:

{
   "document":{
      "relation":[
         {
            "displayURL":"https://firebasestorage.googleapis.com/something.png",
            "status":3,
            "to":"fDI5KVG8xsMz3wbviiiumEeZzYT2",
            "onClick":"fDI5KVG8xsMz3wbviUNumEeZzYT2",
            "from":"Aman Sharma "
         }
      ]
   }
}
Now suppose I want to change the status from 3 to 2. The only thing that comes to my mind is using FieldValue.arrayUnion which is as follows.

public void setRelation(String from,String to,String displayURL,int status) {

        FriendRequest friendRequest=new FriendRequest(from,to,displayURL,status,currUid);
        Map<String, Object> update = new HashMap<>();
        update.put("relation", FieldValue.arrayUnion(friendRequest));

        friendReqs.document(currUid).set(update, SetOptions.merge()).addOnCompleteListener(completionLiveData);
    }

This essentially creates a new object in relation array, with a status equal to 2. But I want to just update particular object in relation array without creating a new one.

Upvotes: 0

Views: 38

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

You will need to read the entire Array in your front-end, modify it and write it back.

Note that, on the other hand, it would be possible if you use a Map instead of an Array, see Update fields in nested objects.

Upvotes: 1

Related Questions