如何按“_createTime”对 firestore 文档进行排序?

rea*_*dul 5 firebase google-cloud-functions firebase-admin google-cloud-firestore

我正在使用带有 Admin SDK 的云 Firebase 函数从我的 Firestore 集合中获取最新文档。排序基于timestamp字段。该值是在编写文档时明确提供的。

获取代码

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())
Run Code Online (Sandbox Code Playgroud)

这些console.log语句打印以下输出。看_createTime在底部。

输出

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来排序文档,而_createTime不是timestamp每次都写入一个值。使用orderBy('_createTime')orderBy('createTime')没有效果。

小智 7

像您当前所做的那样使用字段是正确的方法。您无法对元数据“,_createTime”进行排序。根据https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document:“如果您希望能够按创建日期对文档进行排序,则应该将时间戳存储为字段文件。”