javascriptreactjsfirebasegoogle-cloud-firestore

Firestore Database: How to search for an email in multiple documents


I need to find the ID of a document, and I must do it by comparing the email that each document contains.

This is my database:

enter image description here

For example, I know the email "mipaciente2@gmail.com", and I don't know what document that email is in, what query do I have to do to search each document until I find the one that contains that email?


Solution

  • You just need to have a subcollection reference which is the patients and then create a query using the where() method to find the email field with a specific value. Though, I'm not sure what version you are using. I'll just give the modular and the namespaced versions. See sample snippets below:

    Web Version 9 (modular):

    import { collection, query, where } from "firebase/firestore";
    
    // For `user's-document-id`, I guess you have it.
    const patientsRef = collection(db, "users", "<user's-document-id>");
    
    // Create a query against the collection.
    const q = query(patientsRef, where("email", "==", "mipaciente2@gmail.com"));
    

    Web Version 8 (namespaced):

    var patientsRef = db.collection("users").doc("<user's-document-id>").collection("patients);
    
    // Create a query against the collection.
    var query = patientsRef.where("email", "==", "mipaciente2@gmail.com");
    

    For more information, you may want to check out this documentation.