Home > Back-end >  How to query firebase realtime database to get last month data
How to query firebase realtime database to get last month data

Time:09-04

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

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

enter image description here

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).

CodePudding user response:

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.

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:

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.

  • Related