Firestore query where field is not equal to value using indexes with onSnapshot

烂漫一生 提交于 2020-02-25 08:19:45

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/57908240/firestore-query-where-field-is-not-equal-to-value-using-indexes-with-onsnapshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!