首页 > 解决方案 > 在 Cloud Functions 中执行复合 Firestore 查询

问题描述

我正在编写一些在电影和用户的 Firestore 数据库上工作的触发器。在此触发器中,我试图向新用户显示他选择的类型列表中评分最高的电影。为此,我有一系列他最喜欢的流派,我想在 foreach 循环中查询数据库:

import * as functions from 'firebase-functions';
import { __values } from "tslib";
import * as admin from 'firebase-admin'; 


admin.initializeApp();
const films = admin.firestore().collection("Films");

export const new_user_recommend = functions.firestore
    .document('/Users/{email}')
    .onCreate((snap, context) => {
        const new_user = snap.data();
        if(new_user){
            const new_email = new_user.email;
            const favourite_genres = new_user.favourite_genres;
            let film_id_arr: string[] = new Array();

            favourite_genres.forEach((genre: string) => {
                films.where('genres', 'array-contains', genre).orderBy('avg_rating', 'desc').limit(5).get()
                .then((list_book: any)=>{
                    list_book.forEach((element: any) => {
                        const film_element = JSON.parse(element.data());
                        film_id_arr.push(film_element.data().id);           
                    });
                    return film_id_arr;
                })
                .catch((error: any)=>{
                    console.log(error);
                    console.log("Error loading films");
                });                
            });
        } 
        return 0;            
    });

问题是我总是在 catch 子句中收到错误消息(因此对于数组中的每种类型,我都会收到错误消息)。我再次检查以确保数组中的字符串与每个电影文档的“流派”字段中可能写入的字符串相同。这让我相信我的查询在某种程度上是不正确的。是这样吗?

我编辑以添加一些重要的细节。我得到的确切错误是“无法加载默认凭据”,那么这是否表明用户身份验证而不是查询本身存在问题?

标签: node.jstypescriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


快速搜索后,您的问题似乎是您在使用 firebase-admin 时没有提供有效的凭据website

至少从错误代码来看是这样的。

部署功能的凭据仅对 firebase-admin 是必需的,而对于 firebase-functions 则不需要。


推荐阅读