如何在Firestore中查询嵌套对象

Nik*_*aab 3 nosql dart firebase flutter google-cloud-firestore

我想以以下格式存储数据:

{
   "chatName": "Football",
   "chatMembers":
   [
      {
         "userId": "nSWnbKwL6GW9fqIQKREZENTdVyq2",
         "name": "Niklas"
      },
      {
         "userId": "V3QONGrVegQBnnINYHzXtnG1kXu1",
         "name": "Timo"
      },
   ]
} 
Run Code Online (Sandbox Code Playgroud)

我的目标是让所有的聊天记录,其中在用户与签约userId是在chatMembers列表中。如果已userId登录用户的不在chatMembers属性中,则应忽略该聊天。这可能吗?

如果这不可能,那么我该如何通过子集合来实现呢?

我的开发语言是dart,但是您也可以发布其他语言的解决方案。

我目前的尝试是这样,但这不起作用:

_firestore.collection(collectionName).where("chatMembers.userId", isEqualTo: userId).snapshots()
Run Code Online (Sandbox Code Playgroud)

小智 11

Renaud Tarnec's 是完整的,但并非在所有情况下都有效。只有一个或并非所有字段已知的情况将不会返回预期的文档。但是,通过重构文档中的数据,可以在只有一个字段已知的情况下进行查询,例如用户标识符 (uid)。

这是其中一个文档中的数据结构:

{
  "members": {
    "user4": {
      "active": true,
      "userName": "King Edward III",
      "avatar": "www.photos.gov/animeGirl5.png"
    },
    "user7": {
      "active": true,
      "userName": "Dave K.",
      "avatar": "www.photos.gov/gunsAmericanFlag.png"
    }
  }
Run Code Online (Sandbox Code Playgroud)

这是查询:

{
  "members": {
    "user4": {
      "active": true,
      "userName": "King Edward III",
      "avatar": "www.photos.gov/animeGirl5.png"
    },
    "user7": {
      "active": true,
      "userName": "Dave K.",
      "avatar": "www.photos.gov/gunsAmericanFlag.png"
    }
  }
Run Code Online (Sandbox Code Playgroud)

在此示例中,“user4”表示可能在或可能不在组中的用户。这将返回集合中 uid "user4" 是活动成员的所有文档。这只需知道成员的 UID 即可工作,无需提前知道他们的姓名或头像 uri。

  • 请注意,OP 实际上对数组字段执行查询。 (2认同)

Ren*_*nec 10

Since August 2018 there is the new array_contains operator which allows filtering based on array values. The doc is here: https://firebase.google.com/docs/firestore/query-data/queries#array_membership

It works very well with arrays of string. However, I think it is not possible to query for a specific property of an object stored in the array. One workaround is to query for the entire object, as follows (in Javascript). Of course this may not be feasible in every situation....

    var db = firebase.firestore();
    var query = db.collection('chatDocs').where("chatMembers", "array-contains", { userId: "xyz", userName: "abc" });
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,它不支持查询数组内对象中的单个字段。 (3认同)
  • 不幸的是,您的 firestore 模型必须与您查询集合文档属性的方式完全匹配:( 他们应该解决这个问题。 (2认同)