且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Firebase Cloud Firestore中向文档添加子集合

更新时间:2023-02-14 10:56:07

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

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