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? IssnapShot
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
1 Answer
Reset to default 10OK. 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
版权声明:本文标题:javascript - Using forEach with single document queries in Firestore? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741625880a2389077.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论