首页 > 解决方案 > 如何查询 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;
}

标签: javascriptgoogle-cloud-firestore

解决方案


我只需将顺序从 更改为 就可以使它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;
}

推荐阅读