我正在尝试获取当前用户在对话中所有未见过的消息。问题是我不知道如何排除其他用户看到的消息并仅获取当前用户看到的消息,因此我可以执行 allMessages - allReadMessages = 未读消息计数
这是我试图实现我所解释的功能:
//helper to get unread messages count
async getUnseenMessagesCount(chatAuthor) {
const collectionRef = (await firestore()).collection(this.collectionPath)
try {
collectionRef
.get()
.then(() => {
collectionRef
.where('seenBy', '==', '')
.orderBy('author')
.where('author', '>', store.getters['authentication/user'].id)
.onSnapshot(snapshot => {
snapshot.docChanges().forEach(snap => {
console.log(snapshot.docs.length)
if (snap.type === 'added') {
store.commit(
'chats/setUnreadMessagesCount',
snapshot.docs.length
)
f.push(snapshot.docs.length)
}
})
})
})
.catch(error => {
console.log(error)
}) } catch (error) {
console.log(error)
}
}
这些是 firebase 内的索引(在我的情况下是否需要它们?):
我怎样才能实现我所解释的内容?非常感谢任何帮助!
最佳答案
当我第一次使用firestore时,这些事情对我来说也是一个问题。很难进行简单的计数查询。
因此,对于您的问题,简单的答案是您可以获取经过身份验证的用户 ID 并添加另一个查询,例如
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User logged in already or has just logged in.
console.log(user.uid);
} else {
// User not logged in or has just logged out.
}
});
.where('userId', '==', userId)
但我的建议是使用 firebase 函数来使用 firestore 触发器来计算未见消息的数量。所以在你的函数中你会做类似的事情
const functions = require('firebase-functions');
exports.countUnseenMessages = functions.firestore
.document('...')
.onWrite((change, context) => {
// increase number of unseen messages to the relevant user
});
希望有帮助
关于javascript - 使用带有 onSnapshot 的索引进行 Firestore 查询,其中字段不等于值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57908240/