【问题标题】:How to do arrayUnion on an array of objects inside another array of objects in firebase firestore?如何对firebase firestore中另一个对象数组中的对象数组执行arrayUnion?
【发布时间】:2021-08-06 12:39:43
【问题描述】:

我在我的 react 应用中创建了一个评论部分。评论部分在firestore中具有以下数据结构:-

    comments: [{
        comment: "First comment",
        replies: [{
            reply: "first reply"
        }]
    },{
        comment: "Second comment",
        replies: [{
            reply: "first reply"
        }]
    }]

如果我想添加新评论,我会这样做:-

db.collection("myCollection").doc("0").update({
    comments: firebase.firestore.FieldValue.arrayUnion({
        comment: "New Comment",
        replies: []
    })
})

现在,我真正想做的是为现有评论添加新回复。但我找不到任何方法来做到这一点。例如,我希望在上面定义的数据结构中发生这种情况:-

    comments: [{
        comment: "First comment",
        replies: [{
            reply: "first reply"
        },{
            reply: "second reply"
        }]
    },{
        comment: "Second comment",
        replies: [{
            reply: "first reply"
        }]
    }]

那么我该怎么做呢?

请帮我解决这个问题。 谢谢!

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    您正在尝试通过索引更新数组元素,这不是 Firestore 上的原子操作。

    您需要:

    1. 读取文档并从中检索comments 数组。
    2. 在您的应用程序代码中更新 comments 数组。
    3. 将更新后的comments 数组写回文档。

    如果您要将 cmets 存储在子集合中,您可能可以使用 arrayUnion 来更新特定评论,因为那时回复是该文档中的顶级字段。但我怀疑在这种情况下增加额外文档和文档读取操作的开销是否值得。

    另见:

    【讨论】:

    • 是的,这正是我实际在做的事情。读取整个对象数组,然后在修改后发回。只是想知道是否有一种简单的方法可以做到这一点。无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2020-07-11
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多