没错,与大多数数据库一样,Firestore 不存储创建时间。为了按时间排序对象:
选项 1:在客户端创建时间戳(不保证正确性):
db.collection("messages").doc().set({
....
createdAt: firebase.firestore.Timestamp.now()
})
这里最大的警告是Timestamp.now()使用本地机器时间。因此,如果这是在客户端计算机上运行的,则您无法保证时间戳是准确的。如果您在服务器上设置此设置,或者如果保证顺序不是那么重要,则可能没问题。
选项 2:使用时间戳标记:
db.collection("messages").doc().set({
....
createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
时间戳标记是一个令牌,它告诉 Firestore 服务器在首次写入时设置时间服务器端。
如果您在写入前读取哨兵(例如,在侦听器中),除非您像这样阅读文档,否则它将为 NULL:
doc.data({ serverTimestamps: 'estimate' })
使用以下内容设置您的查询:
// quick and dirty way, but uses local machine time
const midnight = new Date(firebase.firestore.Timestamp.now().toDate().setHours(0, 0, 0, 0));
const todaysMessages = firebase
.firestore()
.collection(`users/${user.id}/messages`)
.orderBy('createdAt', 'desc')
.where('createdAt', '>=', midnight);
请注意,此查询使用本地机器时间 (Timestamp.now())。如果您的应用在客户端上使用正确的时间真的很重要,您可以利用 Firebase 实时数据库的此功能:
const serverTimeOffset = (await firebase.database().ref('/.info/serverTimeOffset').once('value')).val();
const midnightServerMilliseconds = new Date(serverTimeOffset + Date.now()).setHours(0, 0, 0, 0);
const midnightServer = new Date(midnightServerMilliseconds);