首页 > 解决方案 > Firebase 函数:orderBy 函数不起作用

问题描述

以下代码在模拟器中工作,但在includeVideosincludeAudios时在 firebase 中返回一个空数组false

let query = db.collection("content");

if (includeVideos && !includeAudios) {
    query = query.where("type", '==', "video").orderBy("type");
}
if (includeAudios && !includeVideos) {
    query = query.where("type", '==', "audio").orderBy("type");
}
if (!includeVideos && !includeAudios) {
    return {empty json....}
}

if (matchingPersonID != undefined) {
    query = query.where("attributionID", '==', matchingPersonID).orderBy("attributionID");
}

//either categories OR matchingSeriesID is always undefined/empty
if (matchingSeriesID != undefined) {
    query = query.where("seriesIDs", 'array-contains', matchingSeriesID).orderBy("seriesIDs");
}

if (matchingCategories.length != 0) {
    // 'OR' LOGIC
    query = query.where("categories", 'array-contains-any', matchingCategories).orderBy("categories");
}

if (lastDocumentID != undefined) {
    await db.collection("content").doc(lastDocumentID).get().then((snapshot) => {
        query = query.startAfter(snapshot);
        log(`starting after document ${snapshot}`)
    })
}

//the code works when this line is removed, but the query needs to be sorted by time in order for pagination to work
query = query.orderBy("upload_date", "desc");

return query.limit(getNext).get()...

我在谷歌云日志中没有收到错误消息,所以我没有简单的方法来创建索引,如果这是我需要做的。在 firestore 中,字段upload_dateattributionIDtypeseriesIDscategories都在文档中的同一级别。

任何帮助将非常感激!!

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


正如您评论的那样,似乎缺少该字段的索引

本文档提到了两种处理这些索引的方法:

  • 通过使用 CLI。您可以将索引以 JSON 格式保存到本地文件中。为此,firebase firestore:indexes在您的 firebase 项目文件夹中运行,您将获得一个格式化的 JSON 输出供您复制、添加一个新输出,然后使用firebase deploy --only firestore:indexes.

  • 实际上,当 Firebase 捕获使用不存在的索引的错误时,您可以使用由 Firebase 生成的 URL,但您也可以从应用程序的 Firebase 控制台手动执行此操作:

在此处输入图像描述

在此处输入图像描述


推荐阅读