gpt4 book ai didi

javascript - 文档内嵌套集合的 Firestore onSnapshot

转载 作者:行者123 更新时间:2023-12-01 00:32:52 28 4
gpt4 key购买 nike

我正在尝试使用 Firebase->firestore 与 web 建立聊天,因此我尝试将其与 onSnapshot 一起使用,以便用户在打开聊天时能够收到消息。

我的 noSQL 数据库结构如下:

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

enter image description here

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

enter image description here

如果我监听第一个集合“聊天”中具有特定 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"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
const db = firebase.firestore();
</script>

最佳答案

你应该简单地这样做:

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

doc 中所述,“DocumentReference 还可以用于创建子集合的 CollectionReference。”

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

<小时/>

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

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

现在,为什么您的代码在第一种情况下可以工作,而在第二种情况下却不起作用?

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

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

关于javascript - 文档内嵌套集合的 Firestore onSnapshot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58362191/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com