Reputation: 157
I'm trying to retrieve some documents from a collection based on the timestamp falling on a specific day. I know I have documents in my collection that fall between these time stamps but it keeps returning nothing. If I remove the 'startTime' query parameters then I am able to retrieve documents.
Am I querying the timestamps incorrectly?
StartTime stored as timestamp in firestore
// Get bookings from firestore
firestore
.collection('bookings')
.where('studio.ID', '==', 'kM8p1jSenI4M0Mr1PzBo') /// Works fine with this query
.where('startTime', '>=', dayjs(date).valueOf()) /// 1631415616880
.where('startTime', '<', dayjs(date).add(1, 'day').valueOf()) /// 1631502016880
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.table(doc.data());
setBookings(doc.data());
});
Also tried query as a date object:
const [date, setDate] = useState(new Date(new Date().setHours(0, 0, 0, 0))); //setting initial state to current day midnight
const [step, setStep] = useState(0); // Count the days ahead the user is trying to book.
const [alert, setAlert] = useState(false); // Alert when trying to exceed booking window.
const [bookings, setBookings] = useState({});
const bookingWindowAllowed = 7; // Used to limit the forward bookings (evaluated vs state.step)
useEffect(() => {
setLoading(true);
console.log('Set date is:', date);
const setDate = new Date(dayjs(date).valueOf()); //Date object for today
const futureDate = new Date(dayjs(date).add(1, 'day').valueOf()); //Date object for tomorrow
console.log('Set date is:', setDate);
console.log('Future date is:', futureDate);
// Get bookings from firestore
firestore
.collection('bookings')
.where('studio.ID', '==', 'kM8p1jSenI4M0Mr1PzBo') /// Works fine with this query
.where('startTime', '>=', setDate) /// 1631415616880
.where('startTime', '<', futureDate) /// 1631502016880
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.table(doc.data());
setBookings(doc.data());
});
setLoading(false);
})
.catch((error) => {
console.log('Error getting documents: ', error);
setLoading(false);
});
}, [date]);
Upvotes: 3
Views: 698
Reputation: 50930
Try using Firestore Timestamp
object instead of using timestamp in where()
since you are storing it as Timestamp. Also the value is stored in field startTime
so you don't need .seconds
in where()
:
firestore
.collection('bookings')
.where('studio.ID', '==', 'kM8p1jSenI4M0Mr1PzBo')
.where('startTime', '>=', firebase.firestore.Timestamp.fromMillis(dayjs(date).valueOf()))
.where('startTime', '<', firebase.firestore.Timestamp.fromMillis(dayjs(date).add(1, 'day').valueOf()))
.get()
If you need to use the Unix timestamp in query then you would have to store it as number
in Firestore.
Upvotes: 2