文档内嵌套集合的 Firestore onSnapshot

我正在尝试通过网络与 Firebase->firestore 建立聊天,因此我试图让它与 onSnapshot 一起使用,以便用户在打开聊天时能够收到消息。

我已经像这样构建了 noSQL 数据库:

我有一个名为 Chats 的集合,在该集合中我有文档,文档的名称代表 2 个用户之间的关系哈希,该哈希也存储在我的 SQL 数据库中,我的想法是我将使用它作为标识符。

http://img1.mukewang.com/619642220001234612540652.jpg

在每个文档中,都有一个名为“conversations”的集合,其中包含两个用户之间的所有聊天记录。

http://img2.mukewang.com/6196422f0001267612620649.jpg

如果我在第一个集合“聊天”中收听具有特定 id 的文档,如果我更改“时间戳”等字段,我将在控制台中获取日志,以便该部分工作。


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());

    })

});

但是我如何监听目标文档中的“对话”集合?每次在目标文档中添加或编辑新文档时,我都想获取日志


我试过了,但这似乎不是诀窍:)


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());

    })

});

这就是我启动 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"

  };


Smart猫小萌
浏览 129回答 1
1回答

温温酱

你应该简单地做:db.collection('chats').doc('#randomHASH').collection('conversations').onSnapshot((snapshot)&nbsp;=>&nbsp;{...});如文档中所述,“ADocumentReference还可用于创建CollectionReference子集合。”实际上,您可以根据需要多次链接collection()和doc()方法,以获取对任何文档或 (sub-)(sub-)(...) 集合的引用请注意,类似地,在第一种情况下,您可以执行以下操作:db.collection('chats').doc('#randomHASH').onSnapshot((snapshot)&nbsp;=>&nbsp;{...});现在,为什么您的代码在第一种情况下有效,而在第二种情况下无效?在第一种情况下,通过这样做,db.collection('chats').where(firebase.firestore.FieldPath.documentId(), '==', '#randomHASH')您定义了一个query确实有onSnapshot()方法的。但是在第二种情况下,您collection()在同一个上调用一个方法query,而 aquery没有这样的方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript