javascript - 基于昨天在 Firestore 中的“何处”条件?
问题描述
我需要从现场的收集库中获取文档,createdOn
yesterday
但它似乎不起作用。这个查询有更好的解决方案吗?
var startOfToday = new Date();
startOfToday.setHours(0,0,0,0);
var endOfToday = new Date();
endOfToday.setHours(23,59,59,999);
const snapshot = await
firestore().collection(collectionName)
.where('createdOn',CONDITIONS.GREATER_THAN_EQUALS,startOfToday)
.where('createdOn', CONDITIONS.LESS_THAN_EQUALS, endOfToday)
.get();
它给了我result(doc)
来自firestore的createdOn
=今天(当前日期)。
解决方案
如果要获取前一天(昨天)的文档列表,可以使用以下代码片段。
const today = new Date();
today.setHours(0,0,0,0);
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
//For debugging
//console.log("Today: ", today);
//console.log("Yesterday: ", yesterday);
citiesRef = db.collection('cities');
const snapshot = await citiesRef
.where('createdOn', '>=', yesterday)
.where('createdOn', '<', today)
.get();
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
为了使代码正常工作,这是我将数据插入到 Firestore 的方式。
const citiesRef = db.collection('cities');
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
await citiesRef.doc('SF').set({
name: 'San Francisco', state: 'CA', country: 'USA',
capital: false, population: 860000, createdOn: today
});
await citiesRef.doc('LA').set({
name: 'Los Angeles', state: 'CA', country: 'USA',
capital: false, population: 3900000, createdOn: yesterday
});
await citiesRef.doc('DC').set({
name: 'Washington, D.C.', state: null, country: 'USA',
capital: true, population: 680000, createdOn: yesterday
});
await citiesRef.doc('TOK').set({
name: 'Tokyo', state: null, country: 'Japan',
capital: true, population: 9000000, createdOn: today
});
await citiesRef.doc('BJ').set({
name: 'Beijing', state: null, country: 'China',
capital: true, population: 21500000, createdOn: today
});
根据您共享的代码,我看不到您从今天的日期减去一个。
希望这个对你有帮助。
推荐阅读
- python - 无法正确计算 NLTK、Python 3.7.3 中单词形式的频率
- firebase - bitbucket 管道中的 JavaScript 混淆和缩小
- shell - 如何在 linux 中连接到 peap(wpa2)?
- responsive - 如何拥有响应式 Facebook 帖子并获得自动高度
- symfony - 在 symfony 中使用注解时找不到我的路由?
- sql - 如何将Email列的数据从表A移动到B中的Email列并将B的ID返回到新列(EmaiID)作为表A的外键
- javascript - Javascript POST 函数不会通过 webpack 和 symfony 触发
- c - C指针警告的隐式转换
- jenkins - 如何在 Jenkins 管道中强制执行 Junit 报告?
- java - Android Studio 项目在移动到其他文件夹后被删除