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
This is my function that tries to achieve what I explained:
//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)
}
}
These are the indexes inside firebase(are they even needed in my case?):
How can I achieve what I explained? Any help is much appreciated!
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.
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)
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
});
Hope that helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.