如何在 firebase 9 modular 中使用带有实时数据的 Firestore 查询

How to use a Firestore query with realtime data in firebase 9 modular

我希望能够将实时数据用于特定查询,但找不到将查询插入实时逻辑的方法?

import { doc, onSnapshot } from "firebase/firestore";
import { query, orderBy, limit } from "firebase/firestore";  

const query = query(citiesRef, orderBy("name"), limit(3));

const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => {
  const source = doc.metadata.hasPendingWrites ? "Local" : "Server";
  console.log(source, " data: ", doc.data());
});

您只需要在 onSnapshot 中传递查询而不是那个 DocumentReference:

const query = query(citiesRef, orderBy("name"), limit(3));

const unsub = onSnapshot(query, (snap) => {
  
  console.log(" data: ", snap.docs.map(d => d.data());
});