Skip to content
Advertisement

How to add new key to map in Firestore

I want to add new key to a map. memberFees is a field of a document under collection named Faculty I want to store only the key of each member fee inside the memberFees map.

Here is an example of my memberFees map:

enter image description here

I only added that keys in the example manually.

This is what I did:

writeBatches.get(batchIndex).update(db.collection("Faculty")
                .document(faculty.getId()), "memberFees/" + memberFeeId, true);

This code throws an error:

java.lang.IllegalArgumentException: Invalid document reference. Document references must have an even number of segments, but Faculty/7DEj7mlTPBf3cVSCtQO3/memberFees has 3
    at com.google.firebase.firestore.DocumentReference.forPath(DocumentReference.java:81)

Advertisement

Answer

When updating a nested field, use . to separate the field names. Your code uses /, which Firestore interprets as a subcollection.

So:

writeBatches.get(batchIndex).update(db.collection("Faculty")
    .document(faculty.getId()), "memberFees." + memberFeeId, true)
                                     //    👆
Advertisement