簡體   English   中英

將子集合添加到 Firestore

[英]Add subcollection to Firestore

我有一個簡單的網絡聊天應用程序,Firestore 的架構如下所示

- chats (collection)
   - username
      - chats (collection)
         - ohterUsername
            - lastMessage: "hey"
            - lastUpdated: timestamp
            - username: otherUsername

            - messages (collection)
               - createdAt: timestamp
               - message: "hey"
               - from: username
               - to: otherUsername

我添加了兩個字段lastUpdated, lastMessage來跟蹤活動,以便為用戶相應地訂購聊天室。

            await firebase
            .firestore()
            .collection("chats")
            .doc(user.displayName)
            .collection("chats")
            .orderBy("lastUpdated", "desc")
            .limit(1)
            .get()
            .then(function (snapshot) {
              console.log(snapshot.docs);
              if (snapshot.docs.length > 0) {
                snapshot.docs.forEach(doc => {
                    const data = doc.data();
                    // get the user object who last messaged
                    console.log(data); 

                    // check if messages subcollection exists for this user,
                    // if yes, then retrieve the messages  
                    // if not, create it as empty collection so that it will be populated 
                    // when users exchange messages
                    firebase
                    .firestore()
                    .collection("chats")
                    .doc(user.displayName)
                    .collection("chats")
                    .doc(doc.data().username)
                    .collection("messages")
                    .orderBy("createdAt")
                    .get()
                    .then((snapshot) => {
                      snapshot.docs.forEach(doc => {
                        const data = doc.data();
                        console.log(data);
                      });
                    });
                });
            } else {
              console.log("nothing");
            }

對於此用戶,沒有messages子集合,我的問題是如何將其添加為空集合,以便在用戶發送消息后填充它。

您不想創建一個空的子集合,這是一種反模式。

相反,當發送新消息時,請執行

await firestore
  .collection('chats')
  .doc(user.displayName)
  .collection('chats')
  .doc(recipient.displayName)
  .colleciton('messages')
  .add(messageData) // presuming message data contains document data for message

您可以在此處查看有關add方法的文檔。

這將創建一個新集合並同時生成它的第一個文檔。 這也有助於查詢,您可以立即檢查該集合是否存在。


這也超出了問題/答案的范圍。 但我不完全推薦以這種方式保存消息,因為

  1. 存儲更適合保存用戶生成的內容,特別是如果您計划在不久的將來允許用戶發送除純文本消息以外的任何內容。

  2. 如果您決定堅持使用 firestore,那么三個嵌套的子集合似乎非常多余,具體來說是chats -> {userId} -> chats -> {recipientId} -> messages -> {messageId} 相反,您可以將基於收件人 ID 的數據構建為單獨的文檔,即

    - chats/{userId} - messages/{recipientId}: { ...messageData }

    只有當用戶可以與同一用戶打開多個聊天室時,您提出的數據結構才有意義。

集合/子集合不是 Cloud Firestore 中的具體資源,而只是組織文檔和為這些文檔創建的索引的隱式方法。 換句話說,不存在空集合或子集合這樣的東西。 您必須為集合創建一個“樣本”或“虛擬”文檔。

您可以使用占位符文檔創建 subCollection,然后在前端過濾掉該文檔應該很容易,因為它是第一個docs[0]

了解更多https://groups.google.com/g/google-cloud-firestore-discuss/c/o3tUFJpPYKc?pli=1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM