David Reese
David Reese

Reputation: 135

Firebase Functions: orderBy function not working

The following code works in the emulator but returns an empty array in firebase when includeVideos or includeAudios is 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()...

I get no error messages in the google cloud logs, and so I have no easy way of creating an index, if that's what I need to do. In firestore, the fields upload_date, attributionID, type, seriesIDs, and categories are all on the same level in the document.

Any help would be much appreciated!!

Upvotes: 0

Views: 1017

Answers (1)

Cristian Poley
Cristian Poley

Reputation: 246

As you comment, it seems that an index for that field is missing.

This documentation mentions two ways to handle these indexes:

  • By using the CLI. You can bring your indexes to a local file in a JSON format. For this, run firebase firestore:indexes inside your firebase project folder, you'll get a formatted JSON output for you to copy, add a new one and then deploy them with firebase deploy --only firestore:indexes.

  • Indeed, you can use the URL generated by Firebase when it catches the error of using an index that does not exist, but you can also do it by hand from the Firebase console of the application:

enter image description here

enter image description here

Upvotes: 3

Related Questions