【问题标题】:Update nested object in Firebase更新 Firebase 中的嵌套对象
【发布时间】:2019-02-27 15:25:19
【问题描述】:

我正在尝试更新 google 的 Firebase Cloud Firestore 中的嵌套对象。 我的数据库结构是:
集合“用户”
-- 文档 (userId)
---- 集合'矩阵
------ 文档“服务”(获取更多文档:相同类型不同名称)
-------- 成功:故事[]
-------- 失败:故事[]
-------- 名称:字符串

故事模型:
title: string text: string storyType: string ('success' | 'failure) case: string (for instance 'service') ...

现在我正在使用 Angular,我想使用它来更新一个故事。我该怎么做?
我知道如何获取对“服务”文档的引用

update(story: Story, userId:string){ }

db.collection('users').doc(userId).collection('matrix).doc(story.case).update()
我是否需要更新整个文档,或者我可以通过故事对象到达特定的故事(我知道他的类型,例如“成功”并且标题是 uniq),这样我就可以搜索具有这个标题并只更新这个故事?

【问题讨论】:

    标签: angular firebase google-cloud-firestore


    【解决方案1】:

    您可以使用 arrayUnion 和 arrayRemove 运算符在数组中添加和删除元素。

    例如,添加一个故事

      db.collection('users').doc(userId).collection('matrix).doc(story.case).update(
        {"success": FieldValue.arrayUnion(someStory)}
        )
    

    这些运算符将数组视为集合。您不能按索引访问单个项目。

    官方文档在这里:https://firebase.google.com/docs/firestore/manage-data/add-data

    【讨论】:

    • 这适用于添加/删除,但如果我只更改所需故事的属性“文本”,它将添加新故事而不是更新旧故事。我可以删除旧的并添加新的编辑故事,但我不知道这是否是个好主意
    • 我认为 firebase API 没有针对这种情况的更新功能。
    猜你喜欢
    • 2016-02-20
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2023-04-03
    • 2021-12-15
    • 2019-11-02
    相关资源
    最近更新 更多