【问题标题】:Firebase - Create subcollection only if the parent doc existsFirebase - 仅当父文档存在时才创建子集合
【发布时间】:2022-01-10 01:53:10
【问题描述】:

在 Firestore 中,当您删除文档时,您可以指定 {exists: true } 之类的条件,以避免在文档不存在时将其删除。

在并发场景中,如果父文档存在,我们可能只想将文档添加到子集合中。

例如,想象以下 NoSql 结构:

   -comment (doc)
       /likes (subcollection created when the first like is given)
          -like1
          -like2
          ...

有没有可能做类似的事情

likeRef.create(data, { parent_exists: true });

??

是使用 Transactions 处理这种情况的唯一方法(读取父文档,并在 .exists() 为 false 时抛出错误)?

我害怕这种情况,因为如果在删除容器文档的同时创建子集合,数据库中可能会有孤立的“实体”,如果不这样做,甚至可能会破坏 UI为这些极端情况做好准备。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    这在 Firestore 中作为单个操作是不可能的。

    这样做的唯一方法是start a transaction,然后get()事务内的父文档,如果父文档存在,则将文档添加到子集合中。

    【讨论】:

      猜你喜欢
      • 2018-04-03
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多