首页 > 解决方案 > 如何获取firestore中子集合的实时更新?

问题描述

我的数据库包含一个名为“已观看”的子集合,用于观看视频。我希望能够实时跟踪此类子集合。路径如下所示:users/userDocument/watched/date/nestedObjectsForMoviesWatched

例如users/as7f9as98dfa/watched/June-2020/ {name: Forrest Gump, watched: true} {name: Interstellar, watched: false}

这是我尝试处理的方法

  useEffect(() => {
    const unsubscribeWatched = firebase
      .firestore()
      .collection('users')
      .doc(userId)
      .collection('watched')       //why doesn't this work?
      .doc(month)
      .onSnapshot(snapshot => {
        //how to handle snapshot received?
      })

      return () => {
        unsubscribeWatched()
      }

  }, [])

watched当我的应用程序知道对给定对象中的属性进行更改时,这一点尤其重要。

标签: javascriptreactjsgoogle-cloud-firestore

解决方案


文档似乎可以帮助您执行所需的任务。正如您在共享链接中所见,“如果您想在文档或查询元数据更改时接收快照事件,请在附加侦听器时传递侦听选项对象”。因此,只需在代码中添加“includeMetadataChanges: true”,如下所示。完整的例子可以在这里找到。

useEffect(() => {
const unsubscribeWatched = firebase
  .firestore()
  .collection('users')
  .doc(userId)
  .collection('watched') 
  .doc(month)
  .onSnapshot(snapshot => {
    includeMetadataChanges: true
  })

  return () => {
    unsubscribeWatched()
  }}

推荐阅读