我想知道是否可以動態構建 firebase 查詢,目前我正在使用一個變數來確定是否startAfter應該包括在內。
如您所見,這導致重復代碼,僅針對一個變數
export async function fetchUserPhotosPaginated(userId: string, lastUserPhoto?: QueryDocumentSnapshot): Promise<QuerySnapshot> {
if (lastUserPhoto) {
return await getDocs(query(
collection(db, 'photos'),
orderBy('createdAt', 'desc'),
startAfter(lastUserPhoto),
where('user.id', '==', userId),
limit(5)
))
}
return await getDocs(query(
collection(db, 'photos'),
orderBy('createdAt', 'desc'),
where('user.id', '==', userId),
limit(5)
))
}
我試過了
- 使用
startAfter(null),這沒有達到預期的效果 - 將查詢分配給一個變數
let q = query(...),然后使用q = q.startAfter(...)它更新該查詢也不起作用
uj5u.com熱心網友回復:
startAfter有條件地添加的第二種方法是正確的,但更新查詢的語法不正確。嘗試重構函式,如下所示:
export async function fetchUserPhotosPaginated(userId: string, lastUserPhoto?: QueryDocumentSnapshot): Promise<QuerySnapshot> {
// Initial query
let q = query(collection(db, 'posts'), orderBy('createdAt', 'desc'))
// Add startAfter is lastUserPhoto is present
if (lastUserPhoto) q = query(q, startAfter(lastUserPhoto));
// Add remaining conditions
q = query(q, where('user.id', '==', userId), limit(5));
return await getDocs(q)
}
您還可以按照以下答案中的說明在陣列中添加所有條件:
使用 Modular SDK v9 的 Firestore 條件 where 子句
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351475.html
標籤:javascript 火力基地 谷歌云firestore
上一篇:getDownloadURL的Firebase存盤處理錯誤
下一篇:反應UseContext最新值
