【问题标题】:Conditional where clause in firestore queries based on parameters基于参数的firestore查询中的条件where子句
【发布时间】:2019-01-22 14:20:47
【问题描述】:

例如,我的产品列表有动态过滤器列表,从该过滤器列表将 https 请求发送到云功能。然后尝试从该请求中设置多个条件 where 子句

多个条件 where 子句在本地 firebase 应用程序中有效,但在云函数中无效 -- 更新代码 --

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import { Query } from "@google-cloud/firestore"; // update code
const cors = require("cors")({
  origin: true
});
admin.initializeApp();

const settings = { timestampsInSnapshots: true };
admin.firestore().settings(settings);

const database = admin.firestore();

export const getProduct = functions.https.onRequest(
  (request, response) => {
    return cors(request, response, async () => {
      try {
        let productRef = database.collection("product") as Query; // update code
        if(request.query.brand){
          productRef =productRef.where("brand", "==", request.query.brand)
        }
        if(request.query.lifeStyle){
          productRef =productRef.where("lifeStyle", "==", request.query.lifeStyle)
        }
        const productsQuery = await productRef.get();

        const products = productsQuery.docs.map(
          docRef => ({
            id: docRef.id,
            ...docRef.data()
          })
        );
        response.status(200).send(products);
      } catch (error) {
        response.status(500).send(error);
      }
  });
 }
);

编译后控制台显示错误 [ts] 类型 'Query' 不可分配给类型 'CollectionReference'。 [2322]

【问题讨论】:

    标签: typescript google-cloud-firestore google-cloud-functions


    【解决方案1】:

    TypeScript 抱怨您试图更改 productRef 的类型。您首先将调用collection() 的结果分配给productRef。从链接的 API 文档中,您可以看到它返回一个 CollectionReference 类型对象。然后,您尝试使用对where() 的调用结果重新分配productRef,这将返回不同的类型Query。 TypeScript 不喜欢你改变变量的类型。

    由于 CollectionReference 是 Query 的子类,因此您可以直接告诉 TypeScript 您希望将 productRef 作为一个 Query 处理:

    let productRef = database.collection("product") as Query
    

    请注意此处查询的演员表。

    【讨论】:

    • 请告诉我如何将查询导入云功能。
    • 如果您使用 VS Code,它会自动为您提供导入。
    • 更新后代码VS代码自动更新-import {Query} from "@google-cloud/firestore";
    • 然后我尝试在控制台中部署功能错误显示模块“@google-cloud/firestore”未列为 package.json 中的依赖项,然后我手动将 @google-cloud/firestore 添加到包中。 json ,然后运行部署功能它成功部署。但在我发送 https 请求后,它不会返回任何数据或错误
    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多