Reputation: 849
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?
Upvotes: 3
Views: 1610
Reputation: 317362
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.
Upvotes: 6