Home > Enterprise >  How to Query By Firebase Timestamp (from - to)?
How to Query By Firebase Timestamp (from - to)?

Time:08-12

i want to query my data by time stamp

let date = new Date();
var today = new Date();
var yesterday = date.setDate(today.getDate() - 1);
console.log(date)
const dataTable = collection(db, 'sales')
let mquery = query(dataTable, where('createdDate', "<", yesterday))
const qSnap = await getDocs(mquery)
console.log(qSnap)

error : Uncaught (in promise) FirebaseError: Expected type 'mc', but it was: a custom xh object

CodePudding user response:

You should use the query function and create Query instance.

import {query} from "firebase/firestore";

let mquery = query(dataTable, where('createdDate', "<", yesterday))
const qSnap = await getDocs(mquery)

Documentations to refer to:

CodePudding user response:

The error that you encountered was produced by not using the query() method as pointed out by @AyseAsude. Now, after fixing the query, you should also convert the variable yesterday into a date format and iterate the items from the query. See code below:

let date = new Date();
var today = new Date();
var yesterday = new Date(date.setDate(today.getDate() - 1));

const dataTable = collection(db, 'sales')
let mquery = query(dataTable, where('createdDate', "<", yesterday))
const qSnap = await getDocs(mquery)

qSnap.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

For more information, you check out this documentation.

  • Related