I want to remove the type 'A' from the capital. How do I do it? Any code example will be appreciated. I am working on a react project.
CodePudding user response:
As far as I can tell there is no nested array in the document you shared. In that case you can use the arrayRemove
operator to remove a unique item from the array:
const cityRef = doc(db, "cities", "capital");
await updateDoc(cityRef, {
region: arrayRemove({ type: "A" })
});
A few things to note here:
- You can to pass the entire array item to the
arrayRemove
operator, as it only removes array items that exactly and completely match the value you pass. - The
arrayRemove
operations removes all items that match. So if you have multiple{ type: "A" }
items in the array, all will be removed. - This operation can only work on an array field at a known path, it cannot work on an array that is nested under another array.
If your use-case can't satisfy any of the requirements above, the way to remove the item would be to:
- Load the document and get the array from it.
- Update the array in your application code.
- Write the entire top-level array back to the database.
CodePudding user response:
- you have to get the doc and clone properties into temporary object
- you modify your temp object (remove item form region array)
- update original doc with temp object
a cleanest way is to do that throught a firestore/transaction
a small example to have a small approach
const doc = await cityRef('cities/capital').get()
const temp = JSON.parse(JSON.stringify(doc.data()))
temp.region = temp.region.filter(item => item.type !== 'A')
await cityRef('cities/capital').update(temp)