我正在尝试使用FireStore和React JS(Web(构建一个应用程序
我的Firestore数据库基本上有:
- 聊天室
ChatRooms
合集 - 每个聊天室都有许多
messages
,它是一个子集合,例如:
this.db.collection("ChatRooms").doc(phone-number-here).collection("messages")
此外,每个聊天室都有一些客户端信息,如first-name, last-name
等,其中一个非常重要:
lastVisited
,它是一个时间戳(或火戳(
我想我会放一个React Hook,每秒更新lastVisited
字段,这意味着我上次离开聊天室时,尽量在Firestore上准确记录。
基于此,我想检索上次访问后进入的每个客户(聊天室(的所有messages
=>lastVisited
字段。:(
并显示通知。
我已经在messages
子集合和Firestore Transactions
的组合上尝试了.onSnapshot
监听器,但我运气不好。我的应用程序有问题,它一直显示两个,然后一个,然后什么都没有,回到两个,等等,我很痛苦。
这是我的密码!
请原谅我的帮助
unread_messages = currentUser => {
const chatRoomsQuery = this.db.collection("ChatRooms");
// const messagesQuery = this.db.collection("ChatRooms");
return chatRoomsQuery.get().then(snapshot => {
return snapshot.forEach(chatRoom => {
const mess = chatRoomsQuery
.doc(chatRoom.id)
.collection("messages")
.where("from", "==", chatRoom.id)
.orderBy("firestamp", "desc")
.limit(5);
// the limit of the messages could change to 10 on production
return mess.onSnapshot(snapshot => {
console.log("snapshot SIZE: ", snapshot.size);
return snapshot.forEach(message => {
// console.log(message.data());
const chatRef = this.db
.collection("ChatRooms")
.doc(message.data().from);
// run transaction
return this.db
.runTransaction(transaction => {
return transaction.get(chatRef).then(doc => {
// console.log("currentUser: ", currentUser);
// console.log("doc: ", doc.data());
if (!doc.exists) return;
if (
currentUser !== null &&
message.data().from === currentUser.phone
) {
// the update it
transaction.update(chatRef, {
unread_messages: []
});
}
// else
else if (
new Date(message.data().timestamp).getTime() >
new Date(doc.data().lastVisited).getTime()
) {
console.log("THIS IS/ARE THE ONES:", message.data());
// newMessages.push(message.data().customer_response);
// the update it
transaction.update(chatRef, {
unread_messages: Array.from(
new Set([
...doc.data().unread_messages,
message.data().customer_response
])
)
});
}
});
})
.then(function() {
console.log("Transaction successfully committed!");
})
.catch(function(error) {
console.log("Transaction failed: ", error);
});
});
});
});
});
};
搜索它,似乎实现这种比较的最佳选择是使用方法toMillis()
以毫秒为单位转换timestamps
。通过这种方式,您应该能够更好、更容易地比较最后一条消息和最后一次访问的timestamps
的结果——有关该方法的更多信息可以在这里的官方文档中找到。
我相信这将是你最好的选择,正如这里的社区帖子中提到的那样,这将是在Firestore上比较timestamps
的唯一解决方案——有一种叫做isEqual()
的方法,但它对你的用例没有意义。
我建议您尝试一下,使用它来比较您的应用程序的timestamps
。除此之外,社区还有另一个问题-可在此处访问:如何比较火情基地时间戳?-其中用户有与您类似的用例和目的,我相信这可能也会帮助您提供一些想法和想法。
如果这些信息对你有帮助,请告诉我!