简体   繁体   中英

I can't order my firestore data by multiple fields. React

I have a collection called list which I'm trying to order by 3 different fields: important , unimportant and date , so the unimportant come first (they'll be at the bottom of the list, important the last, and all that sorted by timestamp.

If i query to order my docs by any of the above on its own, then it works, trouble starts when I try to put them together as per firestore documentation. So I have the following code:

const q = query(listRef, orderBy("important", "desc"), orderBy("unimportant"), orderBy("date"));

Which gets me Uncaught Error in snapshot listener. This is how i get my data from firestore:

const getData = () => {                                       // get data from firestore to app

onSnapshot(q, (snapshot) => {
  firestoreList = [];
  firestoreIds = [];
  snapshot.docs.forEach((doc) => {
    firestoreList.push({ ...doc.data(), id: doc.id });
    !firestoreIds.includes(doc.id) && firestoreIds.push(doc.id);
  });
  if (firestoreList.length === 0) {
    setItems(items.concat(newItem));
  } else {
    setItemIds(firestoreIds);
    setItems(firestoreList);
  }
});

}

useEffect(() => {
getData();

}, []);

I'm using onSnapshot , because i need the user to be able to add, remove and do other stuff with data and see the outcome reflected immediately for them and for other users who'll be using the app simultaneously.

Ordering/filtering on multiple fields requires that your database contains a so-called composite index on those fields. And unlike single-field indexes, which are created automatically, composite indexes are only created when you explicitly tell the database to do so.

If you log the warning/error message you get, it contains a long direct link to the Firestore console to create the exact index the query needs. The link has all details already filled in, so all you have to do is click the link and then click the button to start creating the index.

Also see:

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