reactjs - 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 });
});
我正在尝试一次做三件事:
- 在一个对象中获取今天的所有约会
- 在对象中获取今天之后的所有约会
- 当约会超过当前时间时,我想将其从数据库中删除
怎么做到呢?
解决方案
您可以做的是在单个查询中获取用户集合中的所有文档,然后遍历每个文档并根据它是过去、今天还是将来对其进行排序。
这是一个例子,评论解释了发生了什么。
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
});
});
推荐阅读
- python-3.x - 如果第 1 列(表 B)存在于第 2 列(表 A)中,则 Pandas 计算第 1 列(表 A)的唯一值
- python - 使用正则表达式在“\”之间提取字符串的感兴趣部分
- python - 对列表/数据框中的元素块进行快速操作
- javascript - 如何在不使用电子表格 ID 的情况下使用 Google 脚本从另一个 Google 表格导入数据
- mongodb - 是否有将 AWS lightail mongoDB 与 mongo Compass 连接的过程?
- c# - 我无法通过 c# 将数据插入 PostgreSql 表,使用函数
- windows - Windows 10 localhost:第 3 方应用程序在尝试连接到 localhost:5146 时挂起,这个端口是什么?
- wordpress - 如何在 wordpress API 中插入元数据?
- imagemagick - 将混合内容的多页 pdf 文件拆分为多个图像
- c# - 在新房间的服务帐户中执行请求时未发现异常