【问题标题】:How do I remove an item from a nested array in Firestore?How do I remove an item from a nested array in Firestore?
【发布时间】:2022-12-01 22:37:28
【问题描述】:

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.

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    As far as I can tell there is nonestedarray 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.

    【讨论】:

      猜你喜欢
      • 2022-12-01
      • 2022-12-02
      • 2022-12-01
      • 2019-07-14
      • 2021-11-18
      • 2022-12-02
      • 2022-01-04
      • 2022-12-01
      • 2022-12-27
      相关资源
      最近更新 更多