Stephanos
Stephanos

Reputation: 571

How can I update an array field with a batch write operation in firestore?

I've been trying to update an array of maps in my document while creating a new document in a sub-collection but couldn't make it work:

export const addTask = async (data, caseId) => {
  let batch = await db.batch();

  const caseRef = db.collection("cases").doc(caseId);
  const taskRef = caseRef.collection("tasks").doc();

  try {
    await batch.set(taskRef, data);
    await batch.set(caseRef, {
      tasks: db.FieldValue.arrayUnion(data),
    }, {merge:true});
  } catch (error) {
    console.log(error);
  }
  return batch.commit();
};

Upvotes: 0

Views: 1269

Answers (1)

Stephanos
Stephanos

Reputation: 571

These are the issues:

  • use batch.update on the second batch call if the array field already exists on the parent doc and just needs to be updated.
  • FieldValue.arrayUnion isn't a method on the client instance of firestore. Use firebase.firestore.FieldValue.arrayUnion from the global firebase namespace to update the array. Check the guide on updating arrays
  • {merge:true} is not required as arrayUnion will add data to the existing set unless it already exists.
    export const addTask = async (data, caseId) => {

      let batch = await db.batch();

      const caseRef = db.collection("cases").doc(caseId);
      const taskRef = caseRef.collection("tasks").doc();

      try {
        await batch.set(taskRef, data);
        await batch.update(caseRef, {
          tasks: firebase.firestore.FieldValue.arrayUnion(data),
        });
       }catch (error) {
        console.log(error);
       }
 
      return batch.commit();
     }

Upvotes: 1

Related Questions