How to add new key to map in Firestore

Issue

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)

Solution

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)
                                     //    👆

Answered By – Frank van Puffelen

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *