如何在Firebase Cloud Firestore中向文档添加子集合 [英] How to add subcollection to a document in Firebase Cloud Firestore

查看:165
本文介绍了如何在Firebase Cloud Firestore中向文档添加子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该文档没有有关如何向文档中添加子集合的任何示例.我知道如何将文档添加到集合中以及如何将数据添加到文档中,但是如何将集合(子集合)添加到文档中?

The documentation does not have any examples on how to add a subcollection to a document. I know how to add document to a collection and how to add data to a document, but how do I add a collection (subcollection) to a document?

应该没有这样的方法:

dbRef.document("example").addCollection("subCollection")

推荐答案

假定我们有一个聊天应用程序,该应用程序的数据库结构类似于以下内容:

Assuming we have a chat application which has a database structure that looks similar to this:

要在文档中写入subCollection,请使用以下代码:

To write a subCollection in a document, please use the following code:

DocumentReference messageRef = db
    .collection("rooms").document("roomA")
    .collection("messages").document("message1");

如果要创建messages集合并调用addDocument(),肯定会花费1000次,但这是Firestore的工作方式.如果需要,您可以切换到Firebase Realtime Database,而写入次数无关紧要.但是,关于Firestore中的支持的数据类型,实际上,可以使用数组,因为受支持.在 Firebase实时数据库中,您也可以使用array ,但这是反模式. Firebase建议不要使用数组的众多原因之一是,它使安全规则无法编写.

If you want to create messages collection and call addDocument() 1000 times will be expensive for sure, but this is how Firestore works. You can switch to Firebase Realtime Database if you want, where the number of writes doesn't matter. But regarding Supported Data Types in Firestore, in fact, you can use an array because is supported. In Firebase Realtime database you could also use an array, but this is which is an anti-pattern. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write.

Cloud Firestore可以存储阵列,它不支持查询阵列成员或更新单个阵列元素.但是,您仍然可以通过利用Cloud Firestore的其他功能来为此类数据建模. 此处是很好解释的文档.

Cloud Firestore can store arrays, it does not support querying array members or updating single array elements. However, you can still model this kind of data by leveraging the other capabilities of the Cloud Firestore. Here is the documentation where is very good explained.

您也不能创建包含1000条消息的子集合并将它们全部添加到数据库中,并且不能同时考虑一条记录.对于每条消息,它将被视为一次写操作.总共进行了1000次操作.上面的图片没有显示如何检索数据,而是显示了一个数据库结构,其中您具有以下内容:

You also cannot create a subcollection with 1000 messages and add all of them to the database and at the same time to consider a single record. It will be considered one write operation for every message. In total 1000 operations. The picture above does not show how to retrieve data, it shows a database structure in which you have something like this:

collection -> document -> subCollection -> document

这篇关于如何在Firebase Cloud Firestore中向文档添加子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆