reactjs - Firestore Timestamp 获取不等于特定日期的集合文档
问题描述
我有一个 Firestore 数据库,其中包含集合中的文档列表。每个文档都有一个预定的日期,它是一种“时间戳”数据类型。我能够在预定日期之前获取数据,但无法获取不等于特定预定日期的所有文档。所以我所做的是在前端过滤了所有不等于预定日期的数据,但是有一个权衡我必须将所有收集文档存储在前端
下面的查询用于按预定日期获取数据。
where: [
[
'ScheduleDateTime',
'>=',
new Date('2020-02-12 00:00:00'),
],
[
'ScheduleDateTime',
'<=',
new Date('2020-02-12 23:59:59'),
],
],
逻辑我内置了不相等日期的前端。
const Quotations =
allDocuments.filter(
ele =>
scheduledDateList.indexOf(
ele.id
) == -1
);
我们已经知道我们不能在 Firestore 中使用!=
或OR
调节。在firestore上工作非常困难。任何建议或解决方案都会有所帮助。
解决方案
正如您在问题中提到的,以及文档中的解释:
Cloud Firestore 不支持以下类型的查询:
- …</li>
- 不支持带有!=子句的查询。在这种情况下,将查询拆分为大于查询和小于查询。...
- 逻辑或查询。在这种情况下,您应该为每个 OR 条件创建一个单独的查询,并在您的应用程序中合并查询结果。
以下函数将根据ScheduleDateTime
时间戳字段合并两个查询:
async function getDatesNotEqual() {
const isLess = datesRef
.where(
'ScheduleDateTime',
'<=',
firebase.firestore.Timestamp.fromDate(
new Date('2020-02-12 00:00:00')
)
)
.get();
const isMore = datesRef
.where(
'ScheduleDateTime',
'>',
firebase.firestore.Timestamp.fromDate(
new Date('2020-02-12 23:59:59')
)
)
.get();
const [isLessQuerySnapshot, isMoreQuerySnapshot] = await Promise.all([
isLess,
isMore
]);
const isLessThanDocsArray = isLessQuerySnapshot.docs;
const isMoreThanDocsArray = isMoreQuerySnapshot.docs;
return _.concat(isLessThanDocsArray, isMoreThanDocsArray);
}
//Here we call the async function
getDatesNotEqual().then(result => {
result.forEach(docSnapshot => {
console.log(docSnapshot.data());
});
});
请注意,我们使用Lodash库来合并两个数组 ( _.concat()
),但您可以使用其他技术来这样做。
另请注意,我们使用fromDate()
Firestore 的方法Timestamp
来构建查询。
推荐阅读
- spring-boot - Spring Boot 2 + Apache Shiro CGLIB 代理
- javascript - 在每一行中添加原型函数而不使用 .prototype=
- python-3.x - 使用 Python 获取乳胶输出高度
- css - 子菜单比它应该下降了一行
- javascript - 直接使用 children 道具和使用 React.Children.toArray 方法的区别
- ios - Tableview Xib 阴影 Swift
- javascript - 使用 jQuery File Upload 上传文件时 JSON 输入错误意外结束
- docker - 如何使用 Singularity 3 构建/运行具有可写文件系统的容器?
- javascript - 传递 React 道具并作为 ObjectName.ObjectName 访问
- apache-spark - 为什么 Dataset.unpersist 级联到所有依赖的缓存数据集?