首页 > 解决方案 > Firestore 查询在获取我需要的 react native 数据时遇到问题

问题描述

await firebase
      .firestore()
      .collection("patients")
      .doc(firebase.auth().currentUser.uid)
      .collection("appointment")
      .orderBy("dateTime", "asc")
      .get()
      .then((result) => {
        let appointment = result.docs.map((doc) => {
          const data = doc.data();
          const id = doc.id;
          const currentDate = moment().format("YYYY-MM-DD");
          const dt=new moment(doc.data().dateTime,'YYYY-MM-DD').format('YYYY-MM-DD');
          if(dt===currentDate){
            return { id, ...data };
          }
        });
        dispatch({ type: GET_APPOINTMENT, appointment });
      });

我正在尝试一次做三件事:

怎么做到呢?

标签: reactjsfirebasereact-nativegoogle-cloud-firestorereact-redux

解决方案


您可以做的是在单个查询中获取用户集合中的所有文档,然后遍历每个文档并根据它是过去、今天还是将来对其进行排序。

这是一个例子,评论解释了发生了什么。

const db = firebase.firestore();

db
  .collection("patients")
  .doc(firebase.auth().currentUser.uid)
  .collection("appointment")
  .orderBy("dateTime", "asc")
  .get()
  .then(async (result) => {
    const pastAppointmentRefs = [], todayAppointments = [], futureAppointments = [];

    // Get current date in YYYY-MM-DD and milliseconds, just the once
    const currentDate = moment().format("YYYY-MM-DD");
    const currentDateMs = Date.now();
    
    result.forEach((doc) => {
      // Get appointment datetime and it's equivalent in milliseconds
      const dateTime = doc.get("dateTime"); // format: YYYY-MM-DD-HH:mm
      const dateTimeMs = moment(dateTime, 'YYYY-MM-DD-HH:mm').valueOf();
    
      // sort appointment based on dateTime
      if (dateTimeMs < currentDateMs) {
        // is in the past, could also be currently taking place
        pastAppointmentRefs.push(doc.ref);
      } else if (currentDate === dateTime.slice(0,10)) {
        // is today
        todayAppointments.push({ id: doc.id, ...doc.data() });
      } else {
        // is in the future
        futureAppointments.push({ id: doc.id, ...doc.data() });
      }}
    });

    // if there are any found appointments in the past, delete them all
    if (pastAppointmentRefs.length > 0) {
      const batch = db.batch();
      // warning! you can only delete up to 500 docs in a single batch
      pastAppointmentRefs.forEach((ref) => {
        batch.delete(ref);
      });
      await batch.commit(); // commit the changes (the deletions)
    }

    // fire the event
    dispatch({
      type: GET_APPOINTMENTS,
      today: todayAppointments,
      future: futureAppointments
    });
  });

推荐阅读