javascript - 如何查询 Firestore 数据库并获取按特定时间戳字段排序的结果
问题描述
我有以下功能,我想用它来查询我的 Firestore 数据库并按发布日期对帖子进行排序。到目前为止,这是我的代码(不工作)我得到了帖子,但它们没有按时间戳排序,最新的在上面。
我的数据库如下所示:
{
postText: "No longer stale posts?"
postTime: February 3, 2021 at 1:32:35 AM UTC-8
userId: "DsZoqkPhbshXsOKOpkcsW3Vh5313"
}
我的代码:
export const getWhere = async (collection, doc, field) => {
const snapshot = await db
.collection(collection)
.where(field, '==', doc) // where("userId" == "currentUserId")
.limit(20)
.orderBy('postTime', 'asc') // "postTime" is a timestamp field.
.get()
.then(function (querySnapshot) {
const final = [];
querySnapshot.forEach(function (doc) {
// doc.data() is never undefined for query doc snapshots
final.push({ ...doc.data(), id: doc.id });
});
return final;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
return snapshot;
}
解决方案
我只需将顺序从 更改为 就可以使它asc
工作desc
。不知道为什么它最初是按照它们存储在数据库中的顺序显示的。希望这对某人有所帮助,需要在firestore的索引部分为此创建一个索引:
posts userId Ascending postTime Descending Collection
export const getWhere = async (collection, doc, field) => {
const snapshot = await db
.collection(collection)
.where(field, '==', doc)
.limit(20)
.orderBy('postTime', 'desc')
.get()
.then(function (querySnapshot) {
const final = [];
querySnapshot.forEach(function (doc) {
// doc.data() is never undefined for query doc snapshots
final.push({ ...doc.data(), id: doc.id });
});
return final;
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
return snapshot;
}
推荐阅读
- typescript - 打字稿记录,无需手动键入键
- javascript - 如何在 svelte 文件中使用电子方法 - Svelte 3 - 还是有其他方法可以做到这一点?
- algorithm - 水合节点
- gremlin - 找不到类的类型标识符:class java.lang.Short
- wordpress - 如果有 2 级,则将唯一的类添加到 0 级
- typescript - PIXI js 加载资产导致缓存警告我纹理已加载到缓存中
- spring-boot - 增加 OAuth 客户端
- c# - 值不能为空。参数名称:path1
- javascript - 在 HTML 表格中输入数据
- javascript - onkeypress() 未调用函数