'Firebase v9 on react JS

I just want to check if i dont create an other chats on my firebase. I query all my chat with this email and then, i check if the array contain the email i wanna tchat with but it doesn't work. I'm using Firebase V9. Anyone has an idea ?

function Sidebar() { const [user] = useAuthState(auth);

const chatRef = collection(db, 'chats');
const qchatExist = query(chatRef, where('users', 'array-contains', user.email) );
const chatsSnapshot = getDocs(qchatExist);

const createChat = () => {

    const input = prompt('Please enter a email adresse');
    if(!input) return;
    if (EmailValidator.validate(input) && !chatAlreadyExists(input) && input !== user.email ) {
        console.log("valide");
        addDoc(collection(db, 'chats'),
        {
            users: [user.email, input],
        });
    }
    else {
        console.log('invalide');
    }
}

const chatAlreadyExists = (data) =>
    !!chatsSnapshot?.docs.find( 
        chat => 
            chat.data().users.find( (user) => user === data)?.length > 0
    );

code



Solution 1:[1]

you probably wanna use Collection Group Queries.

so you can query across all the chats collection at once.

https://firebase.google.com/docs/firestore/query-data/queries#:~:text=We%20can%20use,across%20all%20cities%3A

const users = query(collectionGroup(db, 'users'), where('email', '==', '[email protected]'));

and make sure you create indexes for the query.

Before using a collection group query, you must create an index that supports your collection group query. You can create an index through an error message, the console, or the Firebase CLI.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Otani Shuzo