admin管理员组

文章数量:1295886

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

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));
Share asked Mar 15, 2018 at 10:53 Utkarsh BhattUtkarsh Bhatt 1,6062 gold badges16 silver badges24 bronze badges 2
  • Can't you handle the data inside the forEach loop? Is snapShot an array at that time? – Icepickle 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. – Utkarsh Bhatt Commented Mar 15, 2018 at 11:18
Add a ment  | 

1 Answer 1

Reset to default 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));

本文标签: javascriptUsing forEach with single document queries in FirestoreStack Overflow