Firestore抛出“ onSnapshot()需要1到4个参数”

时间:2019-09-12 08:46:45

标签: javascript firebase vue.js vuejs2 google-cloud-firestore

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

  

FirebaseError:函数Query.onSnapshot()需要1到4之间   参数,但调用时带有0个参数。

这是接收当前所有用户未读消息的帮助程序功能。

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上使用套接字,或者如果推送通知在每台设备上都起作用,那么一切都会变得容易得多。

1 个答案:

答案 0 :(得分:2)

根据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()