Firestore 按文档 ID 进行结构化查询搜索

问题描述 投票:0回答:3

我正在尝试通过文档 id 查询 firestore 集合,但不使用 firestore CLI,而是使用结构化查询(因为我正在使用 Zapier 来自动化某些工作流程)。有没有办法通过记录为字段进行搜索?到目前为止,我已经尝试了以下代码和变体,其中我将 name 替换为“documentId()”、“documentId”,但似乎没有任何效果。当我使用 name 时,出现以下错误:

“错误”: “代码”:400, "message": "key 过滤器值必须是 Key", “状态”:“INVALID_ARGUMENT”

"where": {
    "fieldFilter": {
        "field": {
            "fieldPath": "__name__"
        },
        "op": "EQUAL",
        "value": {
            "stringValue": "THE ID I WANT TO LOOK FOR"
         }
     }
}
firebase google-cloud-firestore zapier
3个回答
3
投票

如果您想使用

__name__
通过 id 获取文档,请将值类型更改为
referenceValue
并提供文档的完整路径,而不仅仅是查询的 id。

"where": {
  "fieldFilter": {
    "field": {
      "fieldPath": "__name__"
    },
    "op": "EQUAL",
    "value": {
      "referenceValue": "projects/project_id/databases/database_id/documents/your_collection/doc_id"
    }
  }
}

0
投票

假设您想使用文档 ID 获取特定文档。您可能需要参考以下代码:

axios.get(`https://firestore.googleapis.com/v1/projects/<Project-ID>/databases/(default)/documents/<Collection-Name>/<Document-ID>`)
    .then(res => {
        console.log(res);
    })
    .catch(error => {
        console.log(error);
    });

上面的代码将获取您想要的特定文档。如果您想获取具有特定字段值的文档 ID,则此处的这一行:

"fieldPath": "__name__"
应该是
fieldName
而不是文档 id。
"fieldPath": "<FieldName>"
。另外,请确保您使用的方法是
POST
。请参阅下面的代码示例以供参考:

axios.post(`https://firestore.googleapis.com/v1/projects/<Project-ID>/databases/(default)/documents:runQuery`,
{
  "structuredQuery": {
      "from": [{
          "collectionId": "<Collection-Name>"
      }],
      "where": {
          "fieldFilter": {
              "field": {
                  "fieldPath": "<FieldName>"
              },
              "op": "EQUAL",
              "value": {
                  stringValue: "<FieldValue>"
              }
          }
      }
  }
}).then(res => { 
  console.log(res) 
})
.catch(error => { 
  console.log(error) 
})

以上所有代码仅供参考,我使用

axios
从Firestore获取数据。

有关更多信息,请查看此文档


0
投票

我正在努力从 name 字段以外的任何地方获取记录。将 name 与 referenceValue 结合使用对我来说效果很好,但其他方法都不起作用。

我需要创建索引或其他什么吗?我正在使用 zapier 来运行查询。

"where": {
  "fieldFilter": {
    "field": {
      "fieldPath": "id"
    },
    "op": "EQUAL",
    "value": {
      "stringValue": "projects/adventure-hunt-323016/databases/(default)/documents/Clues/MxCrAX69e4aYemGUhGHX17"
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.