【发布时间】:2021-02-03 19:47:18
【问题描述】:
我想使用以下函数来查询我的 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;
}
【问题讨论】:
-
您能否编辑您的问题以显示:1) 带有可见
postTime字段的文档的屏幕截图? 2)console.log的postTime值在您的querySnapshot.forEach(function (doc) {代码块中?为此,请显示更新后的代码及其输出。 -
就像弗兰克说的那样,检查/记录您的
timeSatmp字段。还有一点要注意,要获得最新消息,postTime应该按 desc 顺序排列,例如 -orderBy('postTime', 'desc') -
感谢您指出这一点。看起来我脑子有问题,并且在应该是
'desc'时设置了'asc'订单。再次感谢!
标签: javascript google-cloud-firestore