首页 > 解决方案 > 基于昨天在 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=今天(当前日期)。

标签: javascriptgoogle-cloud-firestore

解决方案


如果要获取前一天(昨天)的文档列表,可以使用以下代码片段。

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
});

根据您共享的代码,我看不到您从今天的日期减去一个。

希望这个对你有帮助。


推荐阅读