[英]When data is added to the firestore, I want to listen with onSnapshot so that the data can be called automatically, but I don't know how to use
我想在附图中的数据结构中监听消息的值
我收到此代码错误
secondDb.collection("chats")
.doc(dockey)
.onSnapshot(function (doc) {
doc.docChanges().forEach(function (change) {
if (change.type === "added") {
console.log(doc.data().messages[0]);
} else if (change.type === "modified") {
//
} else if (change.type === "removed") {
//
}
})
});
错误代码 doc.docChanges 不是 function
您可以通过要检索的集合访问数据
var unsubscribe = firestore().collection('chats').onSnapshot(snapshot =>{
snapshot .docChanges().map((change) => {
if (change.type === "added") {
console.log(doc.data().messages[0]);
} else if (change.type === "modified") {
//
} else if (change.type === "removed") {
//
}
})
})
查看您的数据结构,我会说您可能不想在整个集合上调用.onSnapshot
。
您的初始代码很好。 但是,由于您在 DocumentReference 上调用了.onSnapshot
,因此您得到了DocumentSnapshot 。 而不是.docChanges
您只需执行doc.data().messages
。
您还应该查看有关最佳实践的文档以获取实时更新。
如果您正在尝试制作实时消息应用程序,您可以考虑使用 Firebase Cloud Messaging 而不是onSnapshot
。 当用户打开应用程序时,您可以从 Firestore 加载所有对话消息,并在用户连接到互联网时使用 FCM 接收任何新消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.