繁体   English   中英

如何通过 createdAt 在 firebase firestore 中订购评论

[英]How to order comments in firebase firestore by createdAt

我有一个文档,其中有一个对象的注释数组,每个 object 都有 createdAt 属性。 我想使用 createdAt 属性对 comments 数组中的所有评论进行排序,因此,一条新评论会出现在顶部。

我做了一些研究,发现我们可以在firebase 的实时数据库中执行此操作,但我想使用 firestore 对数据进行排序。

这是我的代码:

import { useEffect, useRef, useState } from "react"
// firebase import
import { doc, onSnapshot, orderBy, query } from "firebase/firestore"

import { db } from "../firebase/config"

export const useDocument = (c, id, o) => {
  const [document, setDocument] = useState(null)
  const [error, setError] = useState(null)

  // realtime document data
  useEffect(() => {
    let docRef = doc(db, c, id)

    if (o) {
      docRef = query(docRef, orderBy("createdAt", "desc")) // this is not working
    }

    const unsubscribe = onSnapshot(
      docRef,
      (snapshot) => {
        // need to make sure the doc exists & has data
        if (snapshot.data()) {
          setDocument({ ...snapshot.data(), id: snapshot.id })
          setError(null)
        } else {
          setError("No such document exists")
        }
      },
      (err) => {
        console.log(err.message)
        setError("failed to get document")
      }
    )

    // unsubscribe on unmount
    return () => unsubscribe()
  }, [c, id])

  return { document, error }
}

创建属性: 在此处输入图像描述

query() function 将查询作为参数而不是 DocumentReference。 当从集合中获取多个文档而不是数组元素时, orderBy()子句也会对文档进行排序。

要对数组元素进行排序,您首先需要获取该文档,然后手动对数组进行排序。

const unsubscribe = onSnapshot(
  docRef,
  (snapshot) => {
    // need to make sure the doc exists & has data
    if (snapshot.data()) {
      const orderedArray = snapshot.data().comments.sort((a, b) => a.createdAt.seconds - b.createdAt.seconds);
    } else {
      setError("No such document exists")
    }
  }
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM