简体   繁体   中英

firestore Check if id exists against an array of ids

I developing a simple chat applicaiton for my website using firebase firestore. where every chat session has an id

provided i have an array of ids

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

I want to get all document whose id is equal to any of the id's in the chat_sessions object using the code below.

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

but I am not getting any results.

I come from a PHP/MYSQL background the PHP equivalent of what i am trying to achieve will be sth like this in PHP

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

can anyone help with the right query where we check for document id against a list of ids in an array? Thank You!

Thank you @frank van Puffelen. You were almost right. I should have used in instead of in_array

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

did not work. Instead I replaced in_array with in :

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

This worked! Thank you

Your query is:

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

This checks a field called uid in each document against the values of the chat_sessions .

It seems that instead you want to the check the ID of each document against the array, which you can do with:

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

I found something else on firestore ie "array-contains-any" for this case.

Maybe it's updated now.

火库条件

UPDATE

Hi, firebase did some update recently, so for do it I found out this method

`

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) 
            }
        });
    }})

}, [])`

In this way, you can check how many element in arrays you want (bypassing 10 elements limit of firebase).

Hope can help anyone:D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM