如何在 Firestore 中订购集合中的文档

Fra*_*gne 1 javascript firebase reactjs google-cloud-firestore

我有一个问题,Firebase 版本 9 更新后,我似乎无法弄清楚如何对集合中的文档进行排序。

这是我的代码。我似乎不明白如何在 onSnapshot 中实现 orderBy 。有人可以将我推向正确的方向吗?我已查看文档但找不到解决方案。

import React, { useState, useEffect } from "react";
import SignOut from "./SignOut";
import { Grid, Typography, Avatar } from "@material-ui/core";
import db from "../firebase";
import { onSnapshot, collection, orderBy, query, limit } from "firebase/firestore";
import SendMessage from "./SendMessage";

function ChatBox() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    onSnapshot(collection(db, "messages"), (snapshot) => {
      setMessages(snapshot.docs.map((doc) => doc.data()));
    });
  }, []);
  return (
    <>
      <Grid container>
        <Grid item xs="12" style={{ textAlign: "right" }}>
          <SignOut></SignOut>
        </Grid>
        {messages.map(({ id, text, photoURL }) => (
          <Grid item xs="12" key={id} style={{ marginBottom: "1rem" }}>
            <Avatar alt="" src={photoURL} />
            <Typography>{text}</Typography>
          </Grid>
        ))}
      </Grid>
      <Grid container>
        <SendMessage></SendMessage>
      </Grid>
    </>
  );
}

export default ChatBox;
Run Code Online (Sandbox Code Playgroud)

Fra*_*gne 5

好的,我找到了解决方案:

当您使用 order by 时,如果您尝试对文档进行排序所依据的字段在文档中不存在,则 order by 将不会“存储”并对该文档进行排序。Timestamp接下来,在我的聊天应用程序中,我使用Firebase 提供的构造函数创建了一个字段。这使我能够按顺序订购文件createdAt

我的 ChatBox 文件代码:Chatbox.js

import { collection, query, onSnapshot, orderBy } from "firebase/firestore";
//OTHER CODE
useEffect(() => {
    onSnapshot(query(collection(db, "messages"), orderBy("createdAt")), (snapshot) => {
      setMessages(snapshot.docs.map((doc) => doc.data()));
    });
  }, []);
Run Code Online (Sandbox Code Playgroud)

发送消息.js

import { collection, addDoc, Timestamp } from "firebase/firestore";
//OTHER CODE
const [userMessage, setUserMessage] = useState("");
  async function sendUserMessage(e) {
    const auth = getAuth();
    e.preventDefault();
    const { uid, photoURL } = auth.currentUser;
    await addDoc(collection(db, "messages"), {
      text: userMessage,
      photoURL,
      uid,
      createdAt: Timestamp.fromDate(new Date()),
    });
  }
Run Code Online (Sandbox Code Playgroud)

希望这是有道理的。