簡體   English   中英

在 firestore 中查詢數據並遍歷數組時,有沒有辦法使用 where() function 和“array-contains”

[英]Is there a way to use the where() function and "array-contains" when querying data in firestore and iterate through an array

了解 firestore 並制作一個簡單的活動網站來練習搜索查詢,用戶可以在其中輸入他們的城市 (selectedCity),然后 select 一個活動類別,例如“音樂”、“喜劇”、“酒吧”來過濾活動。

我有一個動態的事件數組。 用戶可以單擊屏幕一側的事件類型,它會根據選擇的類別填充事件數組。 例如:如果我選擇過濾“音樂”、“喜劇”和“酒吧”,那么事件數組將包含這 3 個。

我想知道是否有一種方法可以遍歷數組以查看存儲在 FireStore 中的已發布事件的類別是否與事件數組中的任何事件匹配。

有關如何解決此問題的任何提示都會有所幫助。 現在我只是硬編碼事件[0],其中作為“音樂”顯示所有音樂事件

這是我的查詢代碼:

    const [postsList, setPostsList] = useState([])
    const [value, setValue] = useState("");
    const [selectedCity, setSelectedCity] = useRecoilState(selectedCityState);
    const dbRef = collection(db, "posts");

    const [events, setEvents] = useState([
        "Music",
        "Comedy", 
        "Bars", 
      ])


const getPostsAPI = async () => {
        const data = [];
        const q = query(
                dbRef, 
                where("cityName", "==", selectedCity), 
                where("category", "array-contains", events[0]),
                orderBy("timestamp", "desc"));
        const posts = await onSnapshot(q, (querySnapshot) => {
             querySnapshot.docs.map(d => d.data().length)
            querySnapshot.forEach(doc => {
                data.push(
                    { 
                        companyName: doc.data().companyName,
                        endTime: doc.data().endTime,
                        eventAddress: doc.data().eventAddress,
                        eventDescription: doc.data().eventDescription,
                        startTime: doc.data().startTime,
                        startDay: doc.data().startDay,
                        timestamp: doc.data().timestamp,
                        username: doc.data().username,
                        venueName: doc.data().venueName,
                        imageLink: doc.data().imageLink,
                        startMonth: doc.data().startMonth,
                        startDate: doc.data().startDate,
                        title: doc.data().title,
                        cityName: doc.data().cityName,
                        videoLink: doc.data().videoLink,
                    })
            })
            setPostsList(data);
        }, (error) => {
            console.log(`PostAPI error: ${error}`)
        });
    }

我嘗試將數組作為一個整體傳入,認為 function 可能會將兩者進行比較,但這是不正確的。 試圖找出解決此問題的最佳方法,以及是否必須重組我的代碼。 我知道你最多只能有 10 個 where(),但我認為我不需要這樣做,我也不認為這是最有效的解決方案。

聽起來您正在從數組查詢運算符中尋找array-contains-any

query(
  dbRef, 
  where("cityName", "==", selectedCity), 
  where("category", "array-contains-any", events), // 👈
  orderBy("timestamp", "desc")
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM