首页 > 解决方案 > firebase 的多个单一结果

问题描述

我有一个包含一些 id 的元素数组。我需要连接到 firestore 并仅获取具有每个指定 id 的记录。

我的数组:

    var ids = { 101, 201, 303} 

和我的firestore文件:

{
  "users": {
    {
      "id": 1,
      "name": "name1",
      "otherData:" "otherData"   
    },
    {
      "id": 2,
      "name": "name1",
      "otherData:" "otherData"   
    },
    {
      "id": 3,
      "name": "name1",
      "otherData:" "otherData"   
    },
    ...
    {
    "id": 1000,
    "name": "name1",
    "otherData:" "otherData"   
    }
     
  }

}

如何使用 db.collection('coll1').where() 语句有效地做到这一点?我尝试使用 forEach 来获取数据,如下所示:

ids.forEach(id => {
  let result = db.collection('coll1').where('id', '==', id).get();
  ...
});

但是每次我尝试这样做时,它都不起作用。

我是 firestore 环境的新手,不知道如何进行这样的操作。请帮忙。

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


您可以为此使用 Firstore 复合查询。此处链接到官方文档。

使用 in 运算符可将同一字段上的最多 10 个相等 (==) 子句与逻辑 OR 组合在一起。in 查询返回给定字段与任何比较值匹配的文档。

同样,使用 array-contains-any 运算符将同一字段上的最多 10 个 array-contains 子句与逻辑 OR 组合在一起。数组包含任何查询返回文档,其中给定字段是包含一个或多个比较值的

数组您需要将 id 更改为数组类型

var ids = [ 101, 201, 303 ] 

询问

db.collection("coll1").where("id","in", ids).get();

推荐阅读