How to delete object from array field by array index? or suggest another way!
1 Answer
There is no choose and delete method from an array in cloud firestore. What you can do is get that array to a temporary array and remove the object that you need to delete from the array and overwrite the document array field with your newly updated temporary array.
const deleteObjFromArr = async (index) => {
try {
/*
* Get the files array to a temporary array.
* If you have already gotten the document to an object,
* assign the object field to the temporary array
*/
const docRef = firebase.firestore().collection('tasks-collection').doc('tasks');
const tempArr = (await docRef.get()).files;
// Remove object from array
tempArr.splice(index, 1);
// Save new array in cloud firestore
await docRef.update({ files: tempArr });
console.log('Files array updated successfully');
} catch (err) {
console.log('Error occured. Operation terminated.');
console.log(err);
}
}
2 Comments
Aw KingOftheworld
Now i got another problem, i realise that delete by index bad idea, cause index will change anyway after removal, maybe possible somehow find by some keyword inside array and delete whole array element?
Nimna Perera
yes @AwKingOftheworld, you can. You can use
filter method of array to filter out the array which do not have that finding key. tempArr = tempArr.filter(e => e.attributeName != findingKeyword)