Firebase Firestore Query Between Two Timestamps

不羁岁月 提交于 2020-04-07 10:28:48

问题


I want to find events that are a on now and upcoming (next 30 days) but that are also not in the past.

When i run this as a cloud function, I get "Cannot have inequality filters on multiple properties". How am I meant to get this type of data.

(ignore the fact that the date stuff is a bit messy, am still playing around).

// Create date 30 days in future
const searchData: Date = new Date();
searchData.setDate(searchData.getDate() + 30);

// Load data and handle empty respoonse
const response: admin.firestore.QuerySnapshot = await admin
    .firestore()
    .collection(Collections.EVENTS)
    .where("startDate", "<=", admin.firestore.Timestamp.fromMillis(searchData.valueOf()))
    .where("endDate", ">=", admin.firestore.Timestamp.fromMillis(new Date().valueOf()))
    .where("public", "==", true)
    .limit(NUMBER_OF_EVENTS)
    .get();

Edit: I would like to know the data structure/query method that will allow me to return all events in the events collection that are on now or that will start in the next month. Additionally, I would like the query to exclude events that have already finished. Each document (event) has a startDate and endDate timestamp on it.


回答1:


Since you have two fields to check with ranges, I'm not sure this is doable with a single query. What you can do instead is perform two queries, merge the results on the client, and perform a final filter to get the exact matches.

  1. Make an assumption about the maximum duration for an event. Call that amount of time "X".
  2. Query for all documents where startDate is greater than now - X, and also less than now + 30 days. Call this result set "A".
  3. Query for all documents where endDate is greater than now, and also less than now + 30 days. Call this result set "B".
  4. On the client, iterate all the results from A and B, checking to see if the start and end dates fit the criteria you want.

I can't think of a way to structure your data that will do this with a single query.




回答2:


From the docs:

You can only perform range comparisons (<, <=, >, >=) on a single field, and you can include at most one array-contains or array-contains-any clause in a compound query:

citiesRef.where("state", ">=", "CA").where("state", "<=", "IN");
citiesRef.where("state", "==", "CA").where("population", ">", 1000000);

https://firebase.google.com/docs/firestore/query-data/queries



来源:https://stackoverflow.com/questions/59499798/firebase-firestore-query-between-two-timestamps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!