带有 React Typescript 的 Firebase 9:如何更改 querySnapshot 类型?

Firebase 9 with React Typescript: How do I change the querySnapshot types?

当我尝试将我的查询快照从 firestore it returns 保存为 q: Query<DocumentData> 时,我的查询快照是 querySnap: QuerySnapshot<DocumentData>.

DocumentData 类型是:[field: string]: any; 而且我无法循环遍历它而不会出现任何错误。

我的效果代码

useEffect(() => {
    const fetchListings = async () => {
      try {
        // Get reference
        const listingsRef = collection(db, "listings");

        // Create a query
        const q = query(
          listingsRef,
          where("type", "==", params.categoryName),
          orderBy("timestamp", "desc"),
          limit(10)
        );

        // Execute query
        const querySnap = await getDocs(q);

        let listings: DocumentData | [] = [];

        querySnap.forEach((doc) => {
          return listings.push({ id: doc.id, data: doc.data() });
        });

        setState((prevState) => ({ ...prevState, listings, loading: false }));
      } catch (error) {
        toast.error("Something Went Wront");
      }
    };

    if (mount.current) {
      fetchListings();
    }

    return () => {
      mount.current = false;
    };
  }, [params.categoryName]);

有谁知道如何正确设置我的列表类型?

firestore 中的列表类型应为:

type GeoLocationType = {
  _lat: number;
  _long: number;
  latitude: number;
  longitude: number;
};

export type ListingsDataType = {
  bathrooms: number;
  bedrooms: number;
  discountedPrice: number;
  furnished: boolean;
  geolocation: GeoLocationType;
  imageUrls: string[];
  location: string;
  name: string;
  offer: boolean;
  parking: boolean;
  regularPrice: number;
  timestamp: { seconds: number; nanoseconds: number };
  type: string;
  userRef: string;
};

问题已解决:我所要做的就是:

const listingsRef = collection(
          db,
          "listings"
        ) as CollectionReference<ListingsDataType>;

如您所见,您可以简单地强制引用的类型:

const listingsRef = collection(db, "listings") as CollectionReference<ListingsDataType>;

但是,虽然这有效,但您可能 运行 遇到未来的问题,例如遇到意外类型或您有其他嵌套数据不能很好地转换为 Firestore。

这是泛型类型的预期用途所在,您可以将 FirestoreDataConverter 对象应用于引用以在 DocumentData 和您选择的类型之间进行转换。这通常与 class-based 类型一起使用。

import { collection, GeoPoint, Timestamp } from "firebase/firestore";

interface ListingsModel {
  bathrooms: number;
  bedrooms: number;
  discountedPrice: number;
  furnished: boolean;
  geolocation: GeoPoint; // <-- note use of true GeoPoint class
  imageUrls: string[];
  location: string;
  name: string;
  offer: boolean;
  parking: boolean;
  regularPrice: number;
  timestamp: Date; // we can convert the Timestamp to a Date
  type: string;
  userRef: string; // using a converter, you could expand this into an actual DocumentReference if you want
} 

const listingsDataConverter: FirestoreDataConverter<ListingsModel> = {
  // change our model to how it is stored in Firestore
  toFirestore(model) {
    // in this case, we don't need to change anything and can
    // let Firestore handle it.
    const data = { ...model } as DocumentData; // take a shallow mutable copy

    // But for the sake of an example, this is where you would build any
    // values to query against that can't be handled by a Firestore index.
    // Upon being written to the database, you could automatically
    // calculate a `discountPercent` field to query against. (like "what
    // products have a 10% discount or more?")
    if (data.offer) {
      data.discountPercent = Math.round(100 - (model.discountedPrice * 100 / model.regularPrice))) / 100; // % accurate to 2 decimal places
    } else {
      data.discountPercent = 0; // no discount
    }
    return data;
  },

  // change Firestore data to our model - this method will be skipped
  // for non-existant data, so checking if it exists first is not needed
  fromFirestore(snapshot, options) { 
    const data = snapshot.data(options)!; // DocumentData
    // because ListingsModel is not a class, we can mutate data to match it
    // and then tell typescript that it is now to be treated as ListingsModel.
    // You could also specify default values for missing fields here.
    data.timestamp = (data.timestamp as Timestamp).toDate(); // note: JS dates are only precise to milliseconds
    // remove the discountPercent field stored in Firestore that isn't part
    // of the local model
    delete data.discountPercent;
    return data as ListingsModel;
  }
}

const listingsRef = collection(db, "listings")
  .withConverter(listingsDataConverter); // after calling this, the type will now be CollectionReference<ListingsModel>

这记录在以下位置: