skip to Main Content

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.

2

Answers


  1. 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:

    1. Load the document and get the array from it.
    2. Update the array in your application code.
    3. Write the entire top-level array back to the database.
    Login or Signup to reply.
    1. you have to get the doc and clone properties into temporary object
    2. you modify your temp object (remove item form region array)
    3. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search