我正在尝试根据特定日期的时间戳从集合中检索一些文档。我知道我的收藏中有文件在这些时间戳之间,但它一直没有返回任何内容。如果我删除“startTime”查询参数,那么我就能够检索文档。
我是否错误地查询了时间戳?
StartTime 在 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());
});
还尝试将查询作为日期对象:
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]);
最佳答案
尝试使用 Firestore Timestamp
对象而不是在 where()
中使用时间戳,因为您将其存储为时间戳。此外,该值存储在 startTime
字段中,因此您不需要 where()
中的 .seconds
:
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()
如果您需要在查询中使用 Unix 时间戳,则必须将其作为 number
存储在 Firestore 中。
关于javascript - Firebase firestore 时间戳查询不返回任何文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69139734/