简体   繁体   English

如何按日期对 firebase firestore 文档进行排序?

[英]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.

相关问题 如何在 firebase firestore 中的集合文档之间循环? - How to loop between documents of a collection in firebase firestore? 如何在 Firebase Cloud Firestore 中删除具有相同键值的集合中的文档 - How to delete documents in a collection with the same key value in Firebase Cloud Firestore 如何遍历 Firebase Firestore 文档数组并将值推送到数组中 - How to loop through an array of Firebase Firestore documents and push values into array 如何在本机反应中从 firebase 火库中获取除一份以外的所有文件? - How to get all documents but one from firebase firestore in react native? 如何在 JavaScript SDK 中的 Firebase Firestore 中仅缓存选定的文档 - How to cache only selected documents in Firebase Firestore in JavaScript SDK 如何批量删除 Firebase 云 function 中的 Firestore 文档 - How to do a Batch delete Firestore Documents in a Firebase cloud function 如何使用 reactJS 仅获取 Firebase/Firestore 中的文档列表 - How to get ONLY list of documents in Firebase/Firestore using reactJS Firebase firestore:如何查询相关文档,然后更新每个文档 - Firebase firestore: how to query relevant documents and then update each of them 如何 select 文档在 Firestore 子集合中超过某个日期? - How to select documents in a firestore subcollection that are past a certain date? Firebase Firestore 的日期格式 - Date format for Firebase Firestore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM