[英]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
I want to listen for the value of message in the data structure in the attached image我想在附图中的数据结构中监听消息的值
I get an error with this code我收到此代码错误
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") {
//
}
})
});
error code doc.docChanges is not a function错误代码 doc.docChanges 不是 function
You can access the data over the collection you want to retrieve您可以通过要检索的集合访问数据
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") {
//
}
})
})
Looking at your data structure, I would say that you probably don't want to call .onSnapshot
on your entire collection.查看您的数据结构,我会说您可能不想在整个集合上调用.onSnapshot
。
Your initial code was fine.您的初始代码很好。 But, since you called .onSnapshot
on a DocumentReference, you got a DocumentSnapshot .但是,由于您在 DocumentReference 上调用了.onSnapshot
,因此您得到了DocumentSnapshot 。 Instead of .docChanges
you would just do doc.data().messages
.而不是.docChanges
您只需执行doc.data().messages
。
You should also check out the documentation on Best Practices for realtime updates.您还应该查看有关最佳实践的文档以获取实时更新。
If you're trying to make a realtime messaging app, you might consider using Firebase Cloud Messaging instead of onSnapshot
.如果您正在尝试制作实时消息应用程序,您可以考虑使用 Firebase Cloud Messaging 而不是onSnapshot
。 You could load all the messages for a conversation from Firestore when a user opens the app, and receive any new ones using FCM as long as the user is connected to the internet.当用户打开应用程序时,您可以从 Firestore 加载所有对话消息,并在用户连接到互联网时使用 FCM 接收任何新消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.