简体   繁体   中英

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

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', '==', 'example@hoge.com'));

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.

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