Firebase 9 与 React Typescript:如何更改 querySnapshot 类型?

Uri*_*evi 3 types firebase typescript reactjs

当我尝试从 firestore 保存查询快照时,它返回为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]);
Run Code Online (Sandbox Code Playgroud)

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

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;
};
Run Code Online (Sandbox Code Playgroud)

sam*_*man 7

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

const listingsRef = collection(db, "listings") as CollectionReference<ListingsDataType>;
Run Code Online (Sandbox Code Playgroud)

然而,虽然这有效,但您将来可能会遇到意外类型或其他嵌套数据无法很好地转换为 Firestore 的问题。

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

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>
Run Code Online (Sandbox Code Playgroud)

这记录在以下位置: