Home > Enterprise >  Firebase specific order
Firebase specific order

Time:11-17

I have a collection of items, and within that a Category field that contains 'Breakfast,Lunch,Dinner'

How do I sort these items (index) by Breakfast then Lunch and then Dinner?

Am currently using the following code which is a simple sort alphabetically:

.orderBy("Category", "asc")
.orderBy("Name", "asc")

CodePudding user response:

I honestly don't think there is a way in firebase to create custom sorting schemes. A solution could be to use a Cloud Function. Or you can do this (although I realize it's not very elegant):

let docs = [];
        firebase.firestore().collection('...').where("category","==","breakfast").orderBy("name").get()
        .then((snapshotBreakfast) => {
            snapshotBreakfast.forEach(doc => docs.push(doc.data()));
            firebase.firestore().collection('...').where("category","==","lunch").orderBy("name").get()
            .then((snapshotLunch) => {
                snapshotLunch.forEach(doc => docs.push(doc.data()));
                firebase.firestore().collection('...').where("category","==","dinner").orderBy("name").get()
                .then((snapshotDinner) => {
                    snapshotDinner.forEach(doc => docs.push(doc.data()));
                })
            })
        })

I haven't tested it, but it should work. However I think the idea behind this code is clear.

CodePudding user response:

As shown in the Firebase documentation on data types, string fields are order lexicographically. There is no way to change this.

Two common options:

  1. Store the meal category as a numeric value in the order of your choosing, so 1 being breakfast, 2 being lunch, and 3 being dinner.
  2. Give the meal category a numeric prefix to determine its order, so 1 - breakfast, 2 - lunch, 3 - dinner.
  • Related