ewang
ewang

Reputation: 506

How to update an array within a map using Firestore functions?

I have an array within a map that I want to update using Firestore Functions. My data structure looks like this:

enter image description here

In this case, I want to update the shareRecordsWith array within the {uid} map.

I have been trying to use the following firestore functions but it's not working.

const recordsDict = {"uid": aboutUID, "accessType": accessType}
profilesRef.doc(uid).set({
    [uid]: {
        {'shareRecordsWith': admin.firestore.FieldValue.arrayUnion(recordsDict)},
        {merge: true}
    }
});

Is there a way to update an array within a map through Firestore Functions?

EDIT: Based on the suggestions, I changed the function to

profilesRef.doc(uid).set({
    [`${uid}.shareRecordsWith`]: admin.firestore.FieldValue.arrayUnion(recordsDict)
}, { merge: true })

Unfortunately, then it adds ${uid}.shareRecordsWith as a new field in the document instead of adding to the shareRecordsWith array within the {uid} map.

This is what it looks like:

enter image description here

Upvotes: 0

Views: 477

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

You will need to call out the entire path of the nested field as a single property. You can do this by passing a FieldPath object with update(), but it doesn't look like set() supports this.

profilesRef.doc(uid).update(
    new admin.firestore.FieldPath(uid, "shareRecordsWith"),
    admin.firestore.FieldValue.arrayUnion(recordsDict)
})

Upvotes: 1

Related Questions