I have a Firestore document that contains an array of objects (user-defined email templates). I want to delete an object based on its name. (The idea is that when the user adds a new email template if it has the same name as an existing object, it is deleted and added again, basically updated. But if the name does not exist in the array, it is just added as a new template).
I have read these similar posts, but they are old and seem to refer only to simple arrays of strings, not objects.
How to delete object from array in firestore
how to add or remove item to the the existing array in firestore ?
I have tried of course with ArrayRemove but it doesn't work. The console.logs before and after a run, but nothing is removed from Firestore.
//this either
// 1. (if the template with this name is found): adds a new email template to the list in the User doc
// or 2. (if no template with the same name is found): deletes the template with the same name and adds the new template
const saveNewTemplateExternal = () => {
const nameininput = store.state.currentEmailTemplate.name
const alltemplates = store.state.userData.emailtemplates
let index = -1
if (alltemplates) {
index = alltemplates.findIndex(object => {
return object.name === nameininput;
});
}
if (index > -1) {
alert('found a match')
let templateRef = doc(db, "users", store.state.userData.id)
console.log("will now remove: " + alltemplates[index].name + " : " + alltemplates[index].body)
updateDoc(templateRef, {
emailtemplates: arrayRemove(alltemplates[index])
})
.then(() => {
console.log("removed: " + alltemplates[index].name + " : " + alltemplates[index].body)
})
}
//use current timestamp as id
store.state.currentEmailTemplate.id = Date.now()
let templateRef = doc(db, "users", store.state.userData.id)
updateDoc(templateRef, {
emailtemplates: arrayUnion(store.state.currentEmailTemplate)
})
}
After this function executes, I am left with the old and the new object in Firestore.
Thanks for any help!!