【问题标题】:Firestore query by Object Key按对象键查询 Firestore
【发布时间】:2019-06-23 16:01:50
【问题描述】:

我在 Firestore 的集合中有一系列嵌套对象,它们的键为 UID。我想通过检查他们的 UID 是否是对象键(基本上是否存在)来查询与用户相关的所有文档。这是firestore中的模型:

这就是我目前尝试返回文件的方式:

  getAllTenancyOffersByUserId() {
    return this.afs.collection('collection_name', ref =>
      ref.where(`application.members.${this._auth.currentUserId}`, '==', !null),
    );
  }

但这没有返回任何内容。我知道我可以通过该状态进行查询,但是它会不断更新,因此会导致问题

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore


    【解决方案1】:

    为什么不将 id 添加到对象中?例如

        members: {
          currentMemberId: {
          date_modified:"",
          deposit_type:"",
          status:"pending",
          memberId: "currentMembderId" 
         }
        }
    

    你的查询是:.collection('members').where('memberId', "==", currentMemberId)

    【讨论】:

      【解决方案2】:

      实际上,您可以做的是按对象中的任何字符串字段进行过滤,如下所示:

      .collection("collectionName")
      .where("mapArray.map.stringField", ">", "''")
      

      这里的重要部分是字符串字段; ">", "''"

      【讨论】:

      • 哇,谢谢。这也对我有用。如果您想知道一个键是否包含在一个对象中,试试这个。 (以防万一,但是,如果您有计划进行复合查询,请检查另一个解决方案,因为我们需要为复合查询添加复合索引)
      • 那么映射对象的键是否会作为字符串字段字段保存在每个对象中?
      【解决方案3】:

      我相信不可能查询一个对象是否存在。我认为您在对象内查询字段的想法可能是最好的选择。

      您可以尝试在 date_modified 字段中查询大于 1900 的任何值。

      getAllTenancyOffersByUserId() {
        return this.afs.collection('collection_name', ref =>
          ref.where(`
            application.members.${this._auth.currentUserId}.date_modified`, 
            '>=',
            new Date('1900-01-01')
          ),
        );
      }
      

      【讨论】:

        【解决方案4】:

        以下应该可以解决问题:

          getAllTenancyOffersByUserId() {
            return this.afs.collection('members', ref =>
              ref.where(firebase.firestore.FieldPath.documentId(), '==', `${this._auth.currentUserId}`)
            );
          }
        

        查看对应文档:https://firebase.google.com/docs/reference/js/firebase.firestore.FieldPath#.documentId

        【讨论】:

        • 这不是我要查询的文档 ID
        • 您能否根据您的数据库打印屏幕指出您要查询的内容?
        猜你喜欢
        • 2020-07-09
        • 1970-01-01
        • 2018-05-24
        • 2018-03-26
        • 2019-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多