3

In Firestore, I have a document containing a map called myMap, which contains an array field called myArr.

Is it possible to use arrayUnion to update myArr, by adding an element to it, within a transaction?

await admin.firestore().runTransaction(async (transaction: Transaction) => {
    //

    const docRef: DocumentReference = admin.firestore()
        .doc(`collection/document`);

    const doc: DocumentSnapshot = await transaction.get(docRef);

    if (doc.exists) 
        await transaction.update(docRef,
            {'myMap': {'myArr': FieldValue.arrayUnion('myNewValue')},}
        );

});

I believe the above code should add myArr, but it's instead replacing the entire array.

What am I doing wrong?

1 Answer 1

6

FieldValue.arrayUnion() and FieldValue.arrayRemove() only work when the field identified in the top level of the update object is itself a list. What you're doing now by providing an object with a list is indeed replacing the entire list. It won't recognize the existing contents of that list.

What you can do instead is call out the specific name of the embedded list:

    await transaction.update(docRef,
        {'myMap.myArr': FieldValue.arrayUnion('myNewValue')},}
    );

Note the dot notation for calling out the list specifically.

Sign up to request clarification or add additional context in comments.

1 Comment

How to do it if I want to replace .myArr with a variabel to do the update dynamically ? I tried myMap.${myVar} but it doesnt work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.