为了账号安全,请及时绑定邮箱和手机立即绑定

文档内嵌套集合的 Firestore onSnapshot

文档内嵌套集合的 Firestore onSnapshot

Smart猫小萌 2021-11-18 20:07:09
我正在尝试通过网络与 Firebase->firestore 建立聊天,因此我试图让它与 onSnapshot 一起使用,以便用户在打开聊天时能够收到消息。我已经像这样构建了 noSQL 数据库:我有一个名为 Chats 的集合,在该集合中我有文档,文档的名称代表 2 个用户之间的关系哈希,该哈希也存储在我的 SQL 数据库中,我的想法是我将使用它作为标识符。在每个文档中,都有一个名为“conversations”的集合,其中包含两个用户之间的所有聊天记录。如果我在第一个集合“聊天”中收听具有特定 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"  };
查看完整描述

1 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

你应该简单地做:

db.collection('chats').doc('#randomHASH').collection('conversations').onSnapshot((snapshot) => {...});

文档中所述,“ADocumentReference还可用于创建CollectionReference子集合。”

实际上,您可以根据需要多次链接collection()doc()方法,以获取对任何文档或 (sub-)(sub-)(...) 集合的引用


请注意,类似地,在第一种情况下,您可以执行以下操作:

db.collection('chats').doc('#randomHASH').onSnapshot((snapshot) => {...});

现在,为什么您的代码在第一种情况下有效,而在第二种情况下无效?

在第一种情况下,通过这样做,db.collection('chats').where(firebase.firestore.FieldPath.documentId(), '==', '#randomHASH')您定义了一个query确实有onSnapshot()方法的。

但是在第二种情况下,您collection()在同一个上调用一个方法query,而 aquery没有这样的方法。


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信