簡體   English   中英

firestore 針對 id 數組檢查 id 是否存在

[英]firestore Check if id exists against an array of ids

我使用 firebase firestore 為我的網站開發了一個簡單的聊天應用程序。 每個聊天 session 都有一個 id

假設我有一個 id 數組

chat_sessions = ["q93XhadA9QQLu6X8yfZB", "YXEYISEI8b2iixCcP3VO", "GXrSZbtrmN5NcrtvjFYp"]

我想使用下面的代碼獲取所有 id 等於 chat_sessions object 中任何 id 的文檔。

return this.afs
    .collection('chats', ref => ref.where('uid','in_array',chat_sessions)).snapshotChanges...

但我沒有得到任何結果。

我來自 PHP/MYSQL 背景,PHP 相當於我試圖實現的目標將在 PHP 中像這樣

if(in_array(uid,chat_sessions)){
      get(doc/uid)
      }

任何人都可以幫助我們根據數組中的 id 列表檢查文檔 id 的正確查詢嗎? 謝謝你!

謝謝@frank van Puffelen。 你幾乎是對的。 我應該使用in而不是in_array

ref.where(firebase.firestore.FieldPath.documentId(),'in_array',chat_sessions)

不工作。 相反,我用in替換了in_array

ref.where(firebase.firestore.FieldPath.documentId(),'in',chat_sessions)

這行得通! 謝謝

您的查詢是:

ref.where('uid','in_array',chat_sessions)

這會根據chat_sessions的值檢查每個文檔中名為uid的字段。

相反,您似乎想根據數組檢查每個文檔的 ID,您可以這樣做:

ref.where(firebase.firestore.FieldPath.documentId(),'in_array',chat_sessions)

我在 Firestore 上找到了其他東西,即這種情況下"array-contains-any"

也許現在更新了。

火庫條件

更新

嗨,firebase 最近做了一些更新,所以我發現了這個方法

`

const [products, setProduct] = useState([]);
const ids = ['H11LlJsh3sObwORZhA0b','om9m0lU9HYWyOJZKvEdi','1AoHyHuSFcF01zoyXyTD','6xoBlxsRXUoyzBUcWl0F',
'GJqthlmBGZaFAJqtC2jK','QNT3PxMfhNGg1RZnuqcq','RZgGoFZHyDAYaVZJWxGk','g4UO5P0EgtEqJnawwhXX','gyrZm8p0cEgJdDvTuB1g','mrscldfeYlkaSF151MpI',]

useEffect(() => {
    const saveFirebaseTodos = [];      
    ids.forEach((element) => {
    fetchMyAPI()
    async function fetchMyAPI() {
        const q = query(collection(db, "a"), where('__name__', '==', element));
        const querySnapshot = await getDocs(q); 
        querySnapshot.forEach((doc) => {
        saveFirebaseTodos.push(({id: doc.id, ...doc.data()}));
        /*console.log(doc.id, " => ", doc.data());*/
        if (ids.length == saveFirebaseTodos.length) {
            setProduct(saveFirebaseTodos) 
            }
        });
    }})

}, [])`

通過這種方式,您可以檢查您想要的 arrays 中有多少元素(繞過 firebase 的 10 個元素限制)。

希望可以幫助任何人:D

暫無
暫無

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

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