我正在尝试使用FireStore构建一个应用程序,并对JS (网络)做出反应。
我的Firestore数据库基本上有:
ChatRooms集messages,这是一个子集合,例如:this.db.collection("ChatRooms").doc(phone-number-here).collection("messages")
另外,每个聊天室都有一些客户端信息,如first-name, last-name等,其中一个非常重要:
lastVisited,它是时间戳(或firestamp之类的)
我想我应该设置一个React,它每秒钟更新一次lastVisited字段,这意味着在我上次离开聊天室时,要尽可能准确地记录Firestore。
在此基础上,我想为上次访问后的每一个客户(聊天室)检索所有的messages,
=> lastVisited域:)
出示一份通知。
我尝试过从.onSnapshot侦听器中获得messages子集合,以及Firestore Transactions的组合,但我并不幸运。我的应用程序是错误的,它不断显示两个,然后一个,然后什么都没有,回到两个,等等,我正在遭受很大的痛苦。
这是我的密码!
谢谢你的帮助!
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);
});
});
});
});
});
};发布于 2020-03-26 08:27:31
对其进行搜索,似乎实现此比较的最佳选择是使用timestamps方法toMillis()在毫秒内转换您的toMillis()。这样,您应该能够更好、更容易地比较结果--关于该方法的更多信息可以在官方文档这里中找到--最后消息和最后访问的timestamps。
我相信这将是您最好的选择,正如在这个Community 这里中提到的,这将是在Firestore上比较timestamps的唯一解决方案--有一个叫做isEqual()的方法,但是它对您的用例没有意义。
我建议您尝试使用此方法来比较应用程序的timestamps。除此之外,社区还有另一个问题--这里可以访问:如何比较防火时间戳? --在这里,用户有一个与您相似的用例和目的,我相信这也可以帮助您提供一些想法和想法。
如果这些信息对你有帮助,请告诉我!
https://stackoverflow.com/questions/60860835
复制相似问题