简体   繁体   中英

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!

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});
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM