我正在尝试从 firebase 获取所有当前用户未读的消息。问题是我的 onSnapshot() 返回以下错误,但它在初始加载时返回我所需的值。如果添加了新文档,则 onSnapshot( ) 不会因为该错误而再次触发



这是接收所有当前用户未读消息的辅助函数。

async getUnseenMessagesCount() {
    const collectionRef = (await firestore()).collection(this.collectionPath) //chats/${user_id+second_identifier/messages}
    let allMessagesCount = 0
    let currentUserReadMessagesCount = 0
    try {
      collectionRef.onSnapshot().then(snapshot => {
        allMessagesCount = snapshot.docs.length
      })
      collectionRef
        .where('seenBy', '==', '') // compare against empty string because seenBy is userId.
        .onSnapshot()
        .then(snapshot => {
          currentUserReadMessagesCount = snapshot.docs.length
        })
    } catch (error) {
      console.log(error)
    }

    console.log(allMessagesCount)
    console.log(currentUserReadMessagesCount)
    console.log(allMessagesCount - currentUserReadMessagesCount)
  }

由于我想从用户参与的所有聊天中获取所有未读消息计数,因此我在我的 vuex 操作中执行以下操作,该操作在身份验证状态更改时激活:
new UserChatsDB(newUser.id).readAll().then(snapshot => { //users/id/chats/{chat_id: user_id+second_identifier}
        if (snapshot.length > 0) {
          snapshot.forEach(element => {
            console.log(element)
            const count = new MessagesDB(
              element.chat_id
            ).getUnseenMessagesCount()
            console.log(count) //Returns pending Promise
          })
        }
      })

什么会导致上述错误?有没有更好的方法来解决这个问题?让我知道是否需要数据库结构。任何帮助深表感谢!如果可以在 firebase 上使用套接字,或者如果推送通知可以在每个设备上工作,一切都会容易得多。

最佳答案

根据firebase的docs,你必须像这样使用onSnapshot()函数:

async getUnseenMessagesCount() {
    const collectionRef = (await firestore()).collection(this.collectionPath) //chats/${user_id+second_identifier/messages}
    let allMessagesCount = 0
    let currentUserReadMessagesCount = 0
    try {
      collectionRef.onSnapshot(snapshot => {
        allMessagesCount = snapshot.docs.length
      })
      collectionRef
        .where('seenBy', '==', '') // compare against empty string because seenBy is userId.
        .onSnapshot(snapshot => {
          currentUserReadMessagesCount = snapshot.docs.length
        })
    } catch (error) {
      console.log(error)
    }

    console.log(allMessagesCount)
    console.log(currentUserReadMessagesCount)
    console.log(allMessagesCount - currentUserReadMessagesCount)
  }

所以你必须删除你的 then()

关于javascript - Firestore 抛出 'onSnapshot() requires between 1 and 4 arguments',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57903018/

10-12 17:08