简体   繁体   English

如何查询firebase实时数据库获取上月数据

[英]How to query firebase realtime database to get last month data

How to query data last month or last 2 months based on the timestamp in snapshot this is the question, know I have been able to do that in Firestore like this如何根据快照中的时间戳查询上个月或过去 2 个月的数据这是问题,知道我已经能够像这样在 Firestore 中做到这一点

useEffect(() =>{
  const fetchData = async () => {
  
  const today = new Date()
  const lastMonth = new Date(new Date().setMonth(today.getMonth() - 1))
  const prevMonth = new Date(new Date().setMonth(today.getMonth() - 2))
  
  const lastMonthQuery = query(collection(db,'users'), where('since', '<=', today), where('since', '>', lastMonth))
  
  const lastMonthData = await getDocs(lastMonthQuery)
  
  }
  fetchData()
},[])

how can i write query like this in realtime database?我如何在实时数据库中编写这样的查询? i have tried this code and this is how my database look like我已经尝试过这段代码,这就是我的数据库的样子

在此处输入图像描述

useEffect(()=>{
    const fetchData = async () =>{
      const today = new Date()
      const lastMonth = new Date(new Date().setMonth(today.getMonth() - 1))
      const prevMonth = new Date(new Date().setMonth(today.getMonth() - 2))

      try{
        const dbRef = query(ref(database, 'users/since'), startAt(lastMonth), endAt(today));
        const last = await get(dbRef)
        console.log(last)

         }catch(err){
          console.log(err)
        }
      }
      fetchData()
    },[])

in the console i got this在控制台中我得到了这个

Error: Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).错误:查询:按优先级排序时,传递给 startAt()、startAfter()、endAt()、endBefore() 或 equalTo() 的第一个参数必须是有效的优先级值(null、数字或字符串)。

This code won't work:此代码不起作用:

query(ref(database, 'users/since'), startAt(lastMonth), endAt(today));

This creates a reference to /users/since (which doesn't exist in your screenshot) and then filters them on an implicit value called priority.这会创建对/users/since的引用(在您的屏幕截图中不存在),然后根据称为优先级的隐式值过滤它们。

What you want to do instead is run a query on /users and filter the data on since , which you can do by passing orderByChild to the query:您想要做的是在/users上运行查询并过滤since上的数据,您可以通过将orderByChild传递给查询来完成:

query(ref(database, 'users'), orderByChild('since'), startAt(lastMonth), endAt(today));

Also see the Firebase documentation on ordering data , which you should always do before filtering it.另请参阅有关订购数据的 Firebase 文档,在过滤之前您应该始终这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM