1

How should I write a query for Firestore when I know that the number of document references returned will be only 1?

const query = firebase.firestore().collection('Users').where('mobile', '==', '<some mobile number>').limit(1);

To get the document from this query, I'm using the forEach loop. Is there any way to get the document and its data without using the loop?

let docId;

query.get().then((snapShot) => {
    snapShot.forEach((doc) => {
        docId = doc.id;
    });
    if(docId) {
        // doc exists
        // do something with the data...
    }
}).catch((error) => console.log(error.message));
2
  • Can't you handle the data inside the forEach loop? Is snapShot an array at that time? Commented Mar 15, 2018 at 10:56
  • @Icepickle. That's what I'm not sure of. Even if the thing I query is unique, I have to use the forEach loop which I don't want to for a single document reference. Commented Mar 15, 2018 at 11:18

1 Answer 1

10

OK. I figured it out.

The .docs() method can be used on the snapShot object to get an array of all the documents refs matching the query.

So, if I only have a single document, I can simply access it as follows:

query.get().then((snapShot) => {

    const doc = snapShot.docs[0];

    const docId = doc.id;
    const docData = doc.data();
    // so stuff here...

}).catch((error) => console.log(error.message));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.