Reputation: 571
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
Reputation: 571
These are the issues:
{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