要按时间戳对象排序Firestore中的数据,您可以使用Firestore的orderBy()方法和Firestore的Timestamp数据类型。
以下是一个示例代码,演示如何使用orderBy()方法按时间戳对象排序Firestore数据:
// 导入Firebase和Firestore模块
const firebase = require('firebase');
require('firebase/firestore');
// 初始化Firebase应用
const config = {
// 添加您的Firebase配置信息
};
firebase.initializeApp(config);
// 获取Firestore实例
const db = firebase.firestore();
// 创建一个集合并添加一些文档
async function createCollection() {
const collectionRef = db.collection('myCollection');
// 添加文档到集合中
await collectionRef.add({
name: 'Document 1',
timestamp: firebase.firestore.Timestamp.fromDate(new Date('2022-01-01')),
});
await collectionRef.add({
name: 'Document 2',
timestamp: firebase.firestore.Timestamp.fromDate(new Date('2022-01-03')),
});
await collectionRef.add({
name: 'Document 3',
timestamp: firebase.firestore.Timestamp.fromDate(new Date('2022-01-02')),
});
// 按时间戳对象排序查询结果
const querySnapshot = await collectionRef.orderBy('timestamp').get();
// 打印排序后的结果
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
}
// 调用函数创建集合并按时间戳对象排序
createCollection();
在上面的示例中,我们首先导入Firebase和Firestore模块,然后初始化Firebase应用并获取Firestore实例。
接下来,我们创建一个名为myCollection
的集合,并添加三个文档,每个文档都包含一个名为timestamp
的时间戳字段。
最后,我们使用orderBy('timestamp')
方法对集合中的文档进行排序,并通过get()
方法获取排序后的结果。
在控制台上运行上面的代码,您将看到按时间戳对象排序的结果打印出来。
请注意,由于Firestore是异步操作,我们使用了async/await
来处理异步代码。
下一篇:按时间戳对行数组进行排序