简体   繁体   English

如何获取firestore中子集合的实时更新?

[英]How to get realtime updates for a subcollection in firestore?

My database contains a subcollection called 'watched', for videos watched.我的数据库包含一个名为“已观看”的子集合,用于观看视频。 I'd like to be able to keep track such subcollection in real time.我希望能够实时跟踪此类子集合。 The path looks like this: users/userDocument/watched/date/nestedObjectsForMoviesWatched路径如下所示: users/userDocument/watched/date/nestedObjectsForMoviesWatched

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

Here's how I try to handle it这是我尝试处理的方法

  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()
      }

  }, [])

It is specifically important that my app is aware of when changes are made to the watched property in a given object.特别重要的是,我的应用程序知道何时对给定 object 中的watched属性进行了更改。

It seems like this documentation can help you to perform the task you want. 文档似乎可以帮助您执行所需的任务。 As you can see in the shared link, "If you want to receive snapshot events when the document or query metadata changes, pass a listen options object when attaching your listener".正如您在共享链接中所见,“如果您想在文档或查询元数据更改时接收快照事件,请在附加侦听器时传递侦听选项 object”。 So, it is only necessary to add "includeMetadataChanges: true" in your code, as you can see below.因此,只需在代码中添加“includeMetadataChanges: true”,如下所示。 The complete example can be found here .完整的例子可以在这里找到。

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

  return () => {
    unsubscribeWatched()
  }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM