Smart貓小萌
2021-11-18 20:07:09
我正在嘗試通過(guò)網(wǎng)絡(luò)與 Firebase->firestore 建立聊天,因此我試圖讓它與 onSnapshot 一起使用,以便用戶在打開(kāi)聊天時(shí)能夠收到消息。我已經(jīng)像這樣構(gòu)建了 noSQL 數(shù)據(jù)庫(kù):我有一個(gè)名為 Chats 的集合,在該集合中我有文檔,文檔的名稱代表 2 個(gè)用戶之間的關(guān)系哈希,該哈希也存儲(chǔ)在我的 SQL 數(shù)據(jù)庫(kù)中,我的想法是我將使用它作為標(biāo)識(shí)符。在每個(gè)文檔中,都有一個(gè)名為“conversations”的集合,其中包含兩個(gè)用戶之間的所有聊天記錄。如果我在第一個(gè)集合“聊天”中收聽(tīng)具有特定 id 的文檔,如果我更改“時(shí)間戳”等字段,我將在控制臺(tái)中獲取日志,以便該部分工作。db.collection('chats').where(firebase.firestore.FieldPath.documentId(), '==', '#randomHASH').onSnapshot((snapshot) => { let changes = snapshot.docChanges(); console.log('CHANGES'); console.log(changes); changes.forEach(change => { console.log(change.doc.data()); })});但是我如何監(jiān)聽(tīng)目標(biāo)文檔中的“對(duì)話”集合?每次在目標(biāo)文檔中添加或編輯新文檔時(shí),我都想獲取日志我試過(guò)了,但這似乎不是訣竅:)db.collection('chats').where(firebase.firestore.FieldPath.documentId(), '==', '#randomHASH').collection('conversations').onSnapshot((snapshot) => { let changes = snapshot.docChanges(); console.log('CHANGES'); console.log(changes); changes.forEach(change => { console.log(change.doc.data()); })});這就是我啟動(dòng) Firebase 的方式<!-- The core Firebase JS SDK is always required and must be listed first --><script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-app.js"></script><!-- The core Firebase JS SDK is always required and must be listed first --><script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-firestore.js"></script><!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries --><script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-analytics.js"></script><script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "xxxxxxxxx", authDomain: "myapp-xxxxx.firebaseapp.com", databaseURL: "https://myapp.firebaseio.com", projectId: "myapp-xxxxx", storageBucket: "myapp-xxxxx.appspot.com", messagingSenderId: "xxxxxxxxx", appId: "1:xxxxx:web:xxxx", measurementId: "x-xxxxxx" };
1 回答

溫溫醬
TA貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
你應(yīng)該簡(jiǎn)單地做:
db.collection('chats').doc('#randomHASH').collection('conversations').onSnapshot((snapshot) => {...});
如文檔中所述,“ADocumentReference
還可用于創(chuàng)建CollectionReference
子集合?!?/p>
實(shí)際上,您可以根據(jù)需要多次鏈接collection()
和doc()
方法,以獲取對(duì)任何文檔或 (sub-)(sub-)(...) 集合的引用
請(qǐng)注意,類似地,在第一種情況下,您可以執(zhí)行以下操作:
db.collection('chats').doc('#randomHASH').onSnapshot((snapshot) => {...});
現(xiàn)在,為什么您的代碼在第一種情況下有效,而在第二種情況下無(wú)效?
在第一種情況下,通過(guò)這樣做,db.collection('chats').where(firebase.firestore.FieldPath.documentId(), '==', '#randomHASH')
您定義了一個(gè)query
確實(shí)有onSnapshot()
方法的。
但是在第二種情況下,您collection()
在同一個(gè)上調(diào)用一個(gè)方法query
,而 aquery
沒(méi)有這樣的方法。
添加回答
舉報(bào)
0/150
提交
取消