Shi*_*tel 5 javascript firebase reactjs google-cloud-firestore
我正在使用 firebase 和 React js 创建一个实时聊天应用程序。我创建了一个 const Functions = require('firebase-functions'); 在 firebase 中称为“聊天”。该集合包含唯一的room_ID(发送者和接收者的组合),并且该文档再次包含称为“消息”的子集合。消息中的每个集合都包含消息、时间、sender_id 和读取状态等信息。
现在,每次当我在聊天列表中收到新消息时,我都必须更新对话。我使用Reactjs的componentDidMount()方法并编写以下代码:
firestore.collection('chats').doc("b7EuhNpdzXUlxhSgDkn2a6oReTl1_OZbrlH8FjmVFqSAtAc0A6TUHS3I3").collection("messages")
.onSnapshot(querySnapshot => {
console.log("querySnapshot", querySnapshot)
querySnapshot.docChanges().forEach(change => {
console.log("change", change)
if (change.type === 'added') {
this.setState({messages : [...this.state.messages, change.doc.data()]});
console.log('New city: ', change.doc.data());
}
if (change.type === 'modified') {
console.log('Modified city: ', change.doc.data());
}
if (change.type === 'removed') {
console.log('Removed city: ', change.doc.data());
}
});
});
Run Code Online (Sandbox Code Playgroud)
您可以在此处看到,它仅适用于单个房间(b7EuhNpdzXUlxhSgDkn2a6oReTl1_OZbrlH8FjmVFqSAtAc0A6TUHS3I3)。我想以这样的方式编写查询,它会监听每个联系人的消息。为此,我必须删除特定文档的限制。
请帮我。
先感谢您。
这是 Firebase 数据库的结构。
我相信获取您想要的数据的一些更好的方法是:
将 Firestore 重组为仅包含一个messages集合,如以下示例结构所示:
messages collection
uid
receiverUserId
senderUserId
msg
read
time
Run Code Online (Sandbox Code Playgroud)
通过这种方法,您可以过滤您正在观看的文档,例如当前经过身份验证的用户从多个用户接收的文档,方法如下:
firestore.collection("messages")
.where("receiverUserId", "==", authUid)
.onSnapshot(function(querySnapshot) {
//do whatever
});
Run Code Online (Sandbox Code Playgroud)
创建多个侦听器,每个chats文档一个,以监视其后续messages子集合。所以你可以做这样的未经测试的代码:
firestore.collection('chats').get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var eachChatRef = firestore.collection('chats').doc(doc.documentID)
var messagesRef = eachChatRef.collection("messages");
messagesRef.onSnapshot(function(snapshot) {
snapshot.docChanges().forEach(function(messageDoc) {
// Do whatever
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3376 次 |
| 最近记录: |