代码之家  ›  专栏  ›  技术社区  ›  r121

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

  •  1
  • r121  · 技术社区  · 3 年前

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

    我做了一些研究,发现我们可以在 firebase's real-time database 但我想用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 }
    }
    
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Dharmaraj    3 年前

    这个 query() 函数将查询作为参数,而不是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.getTime() - b.createdAt.getTime());
        } else {
          setError("No such document exists")
        }
      }
    )