【发布时间】: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