【发布时间】:2021-12-17 06:58:30
【问题描述】:
以下代码在模拟器中有效,但当 includeVideos 或 includeAudios 为 false 时,在 firebase 中返回一个空数组:
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_date、attributionID、type、seriesIDs 和 categories 字段在文档中都处于同一级别。
任何帮助将不胜感激!
【问题讨论】:
-
当
matchingPersonID和matchingCategories同时给出时,您应该抛出自己的错误,因为同时使用两者会导致 Firebase 出错,但从您处理的方式来看并不明显当两者都给出时。 -
如果可以的话,还可以考虑使用模块化 Firebase V9 语法,因为每个约束都可以添加到数组中,然后一次性合并到查询中。这使您可以避免在每隔一行重新定义查询并将其切换为使用
const。 -
我确实抛出了一个错误,但我没有发布该代码。不过谢谢!
-
我试图弄清楚如何升级到 v9,但我似乎无法弄清楚。这是否意味着我需要重写所有函数?
-
另外,我刚刚注意到
type和attributionID上的orderBy会抛出错误,因为您将它们与等式一起使用。关于升级到v9,可以通过导入firebase/compat/app、firebase/compat/firestore等方式导入兼容库逐步迁移代码。然后当你想使用现代语法时导入firebase/firestore等等。
标签: javascript node.js firebase google-cloud-firestore google-cloud-functions