【问题标题】:Query Firestore collection by object按对象查询 Firestore 集合
【发布时间】:2018-01-26 02:22:35
【问题描述】:

我创建了一个名为“books”的集合,并在其中创建了一个名为“users”的对象(又名 dict)。该对象如下所示:

users: {
    5PPCTcdHOtdYjGFr7gbCEsiMaWG3: firebase.firestore.FieldValue.serverTimestamp()
}

现在我想查询属于某个用户的所有书籍。我试过这个:

this.db
  .collection('books')
  .where(`users.${this.state.currentUser.uid}`, '>', 0)
  .onSnapshot(querySnapshot => {
      ...

我从来没有收到任何文件退还。我确定它应该匹配的东西。

为了检查我的理智,如果我删除 where(...) 部分,我会得到文件。只是我得到了所有用户的文档。

我在控制台中将该字符串记录在 .where() 中,它看起来是正确的。

【问题讨论】:

  • 作为一个短期解决方案,我遍历所有文档并比较每个doc.data().users。但这不是一个好的解决方案。

标签: firebase google-cloud-firestore


【解决方案1】:

您的查询是错误的,因为您将日期对象与数字进行比较,因此是两个不同的东西。您可以通过运行下面的这两行代码来检查它。

  console.log(typeof(firebase.firestore.FieldValue.serverTimestamp()))
  console.log(typeof(0))

所以你有两个选择:

1 - 您可以将日期对象与数据对象进行比较,如下所示。

this.db
  .collection('books')
  .where(`users.${this.state.currentUser.uid}`, '>', new Date(0))
  .onSnapshot(querySnapshot => {
      ...

2 - 或者您可以以毫秒为单位保存日期并将其与数字进行比较。

users: {
    5PPCTcdHOtdYjGFr7gbCEsiMaWG3: new Date().getTime();
}

 this.db
      .collection('books')
      .where(`users.${this.state.currentUser.uid}`, '>', 0)
      .onSnapshot(querySnapshot => {
          ...

【讨论】:

    【解决方案2】:

    我也不能让它与.where() 一起使用,但它似乎可以使用.orderBy(),替换:

    .where(`users.${this.state.currentUser.uid}`, '>', 0)
    

    .orderBy(`users.${this.state.currentUser.uid}`)
    

    【讨论】:

    • 是的,似乎 orderBy 本身就足够了,但谁知道它可能会使用 new Date(0) 更改更安全
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 2019-10-02
    • 2020-11-21
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多