【问题标题】:Firestore orderBy Timestamp objectFirestore orderBy Timestamp 对象
【发布时间】:2020-11-06 10:49:19
【问题描述】:

我正在尝试按时间戳排序查询。

在我的文档中,我有一个名为“日期”的字段,它具有以下形式:

date = {
   nanoseconds: 963000000,
   seconds: 1594917688
}

在我的代码中我有这个:

let photosArray = [];

firebase
  .getDatabase()
  .collection("photos")
  .doc(firebase.getCurrentUser().uid)
  .collection("userPhotos")
  .orderBy("date", "asc") // Sorted by date in ascending direction
  .onSnapshot((snapshot) => {
      let changes = snapshot.docChanges();
      changes.forEach((change) => {
         if (change.type === "added") {
            // Get the new photo
            const photo = change.doc.data();

            // Add the photo to the photos list
            photosArray.push(photo);
          }
       });

       // The last photo is at the top of the list
       setPhotos(photosArray);

但是当我渲染照片列表时,它们是未排序的……例如:第一张是 2 小时前拍摄的,第二张是 1 分钟前拍摄的,最后一张是 2 年前拍摄的。

更新

这就是我在 Firestore 中存储日期的方式

Firebase.js:

getTimestamp = () => firebase.firestore.FieldValue.serverTimestamp();

PhotoUploader.js

 await firestore
    .collection("photos")
    .doc(userId)
    .collection("userPhotos")
    .add({
        id,
        date: firebase.getTimestamp(),
     });

【问题讨论】:

  • 您的“日期”字段是否使用 Firebase 时间戳类型?例如,如果您登录到 Firebase 控制台,则日期当前存储为时间戳(而不是数字或字符串)。
  • 是的,我正在使用 firebase.firestore.Timestamp.fromDate(new Date())

标签: javascript reactjs firebase react-native google-cloud-firestore


【解决方案1】:

如果您的日期字段显示包含两个嵌套字段的地图,则这并不是真正的时间戳,并且不会按照您期望的方式进行排序。您应该查看将日期字段添加到文档的代码,并确保它正确使用了时间戳。要么这样,要么使用单个时间戳数值,按照您期望的方式进行排序。

【讨论】:

  • 我正在使用 firebase.firestore.Timestamp.fromDate(new Date()) 来存储日期
  • 因为在 firestore 中没有 Date 类型,并且 firebase.firestore.Timestamp.fromDate(new Date()) 返回一个地图...如果我使用字符串来存储日期?此外,我曾想过只存储秒数并忽略纳秒数,但它可能会无法正常工作。
  • 你可以只写一个 Date 对象。 Firestore SDK 会将其转换为 Firestore 时间戳。如果不查看所有相关代码,就不可能看到您可能做错了什么。但是,如果您看到两个字段像这样分开,那您肯定做错了。
  • 我已经更新了这个问题。现在你可以看到我是如何存储日期的。问题是,在本文档firebase.google.com/docs/reference/js/… 中,时间戳具有我所说的这两个属性(秒 + 纳秒),但我想如果我像我一样执行 orderBy("date"),它将按地图实例本身
  • 使用new Date()设置日期字段,或firebase.firestore.FieldValue.serverTimestamp()使用服务器时间。
猜你喜欢
  • 2020-01-18
  • 2019-04-21
  • 2021-03-06
  • 1970-01-01
  • 2015-02-11
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多