【问题标题】:How can I query a firestore database and get the results sorted by a specific timestamp field如何查询 Firestore 数据库并获取按特定时间戳字段排序的结果
【发布时间】: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.logpostTime 值在您的 querySnapshot.forEach(function (doc) { 代码块中?为此,请显示更新后的代码及其输出。
  • 就像弗兰克说的那样,检查/记录您的timeSatmp 字段。还有一点要注意,要获得最新消息,postTime 应该按 desc 顺序排列,例如 - orderBy('postTime', 'desc')
  • 感谢您指出这一点。看起来我脑子有问题,并且在应该是 'desc' 时设置了 'asc' 订单。再次感谢!

标签: javascript google-cloud-firestore


【解决方案1】:

只需将顺序从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;
}

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 1970-01-01
    • 2020-01-26
    • 2020-07-20
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 2021-04-25
    相关资源
    最近更新 更多