[英]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:我有一个 firebase firestore 集合,其中包含多个具有随机 ID 的文档,当我使用以下代码显示它们时:
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.它确实按它们的 ID 对文档进行排序,我想做的是按日期对它们进行排序,以便最新的是第一个,最后是最旧的。
By the way I have an map in each document with this format:顺便说一句,我在每个文档中都有一个 map,格式如下:
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.鉴于您正在使用的数据 model ,您希望使用 Firestore 进行查询是不可能的。 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.这可以是一个数字(可能是以毫秒为单位的纪元时间)或 Firestore 时间戳,但它必须是单个字段,而不是具有细分时间部分的 6 个字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.