Cloud Firestore Data Model 介紹

collection & document

Cloud Firestore 的 database 主要分成 collection & document 兩種東西。document 代表我們的資料,比方我們可以用 document 儲存每首歌的相關資訊,像是歌名,歌手等,所以十首歌將有十個 document。而 document 會被裝在 collection 裡,所以我們可以用一個 songs collection 儲存 10 首歌的 document。

範例

songs collection 裡有三首歌的 document
users collection 裡有兩個 user,alovelace & aturing

array & map

document 的內容除了常見的數字,字串外,也可以儲存簡單的 array 或 map(dictionary)。如下圖所示,name 的內容是 map,rooms 的內容是 array。

在 Firebase console 輸入 document 內容時,可從 Type 欄位選擇 map & array。

subcollections

document 裡也可以利用 subcollection 儲存其它的 document,比方開發聊天 App 時,collection rooms 儲存代表聊天室的 document,然後聊天室 roomA document 存著 collection messages,在 messages 裡存著代表每則聊天訊息的 document。

如下圖所示,我們可在 document 裡點選 Add collection 加入 collection。

為什麼要在聊天室 document 裡使用 collection 儲存聊天訊息呢 ? 當然我們也可以用 array 或 map 儲存聊天訊息,不過我們人緣那麼好,那麼會聊天,當聊天訊息愈來愈多時,聊天室 document 將變得愈來愈大,造成較慢的 document 存取時間。

而使用 collection 儲存聊天訊息的寫法則彈性多了,它讓我們可以應付大量的聊天訊息。到時候即使聊天訊息愈來愈多,聊天室 document 佔用的空間也不會增加,不會讓存取速度變慢。

因此,在 Cloud Firestore 的 database 裡,collection 下有 document,document 裡可以有 collection,所以我們可以打造非常複雜的架構,比方在 collection music 下有個 document 周杰倫,在 周杰倫下有 collection albums,在 albums 下有 document 葉惠美,在葉惠美下有 collection songs,songs 下有 document 晴天。根據官方文件的說明,目前可以支援到 100 層呢。

Documents in subcollections can contain subcollections as well, allowing you to further nest data. You can nest data up to 100 levels deep.

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com