astrojams1
astrojams1

Reputation: 1591

How do I get documents from Firebase / Firestore ordered by property value

I have 6 documents in a "categories" collection that look like:

{
  color: "#eee",
  index: 6,
  name: "Restaurants",
}

I want to retrieve these documents ordered by the index property, ordered from least to most. I am able to get all the documents, but I'm not sure how to order the results by index. I am also not sure whether I should query them from Firestore and then only order them once they are on the client.

Today my query looks like:

var db = firebase.firestore();    
db.collection("categories").get().then((querySnapshot) => {
      let categories = []
      querySnapshot.forEach((doc) => {
        categories.push(doc.data())
      });
      this.setState({categories: categories});
    });

Thank you!

Upvotes: 0

Views: 2077

Answers (1)

astrojams1
astrojams1

Reputation: 1591

Hi astrojams1 great question. Modify your query as so:

db.collection("categories").orderBy("index")
  .get()
  .then((querySnapshot) => {
    let categories = []
    querySnapshot.forEach((doc) => {
      categories.push(doc.data())
    });
    this.setState({categories: categories});
  });

Upvotes: 1

Related Questions