简体   繁体   中英

How to sort firebase firestore documents by date?

I have a firebase firestore collection with multiple documents with random IDs, when I show them using this code:

import { collection, getDocs } from "firebase/firestore";

const querySnapshot = await getDocs(collection(db, "cities"));
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

It does sort the documents by their IDs, what I want to do is sort them by the date, so that the newest is the first and the oldest in the end.

By the way I have an map in each document with this format:

date: {
     y: /* year */,
     m: /* month */,
     d: /* day */,
     h: /* hour */,
     mi: /* minute */,
     s: /* second */
}

The query you're hoping for is not possible with Firestore given the data model you're working with. If you want to sort by timestamp, you will need a single field that represents the time. This can be either a number (perhaps epoch time in milliseconds) or a Firestore timestamp, but it needs to be a single field, not 6 fields with broken down time parts.

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