使用onSnapshot的索引对字段不等于值的Firestore查询 [英] Firestore query where field is not equal to value using indexes with onSnapshot
问题描述
我正在尝试获取当前用户正在对话的所有看不见的消息.问题是我不知道如何排除其他用户看到的消息,而仅获取当前用户看到的消息,因此我可以执行allMessages - allReadMessages = unread messages count
I am trying to get all unseen messages that the current user has in conversation. The problem is that I do not know how to exclude other user seen messages and get only current user seen messages so I can do allMessages - allReadMessages = unread messages count
这是我的功能,试图实现我所解释的内容:
//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内部的索引(在我的情况下甚至需要它们吗?):
如何实现我的解释?任何帮助深表感谢!
How can I achieve what I explained? Any help is much appreciated!
推荐答案
当我第一次使用Firestore时,这些事情对我来说也是一个问题.很难执行简单的计数查询.
When I user firestore for the first time, these things was also a problem for me. Being very hard to do a simple count query.
因此,对于您的问题,简单的答案是您可以获取经过身份验证的用户ID,并在其中添加另一个查询之类的内容
So for your question, the simple answer is you can get the authenticated user id and add another where query something like
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触发器计算看不见的消息数.因此,在您的函数中,您将执行以下操作
But my suggestion is to use a firebase function to count the number of unseen messages using firestore triggers. So in your function you would do something like
const functions = require('firebase-functions');
exports.countUnseenMessages = functions.firestore
.document('...')
.onWrite((change, context) => {
// increase number of unseen messages to the relevant user
});
希望有帮助
这篇关于使用onSnapshot的索引对字段不等于值的Firestore查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!