Issue
Im trying to look for a document where value "phone" is equal to the phone number that was input by the user
ive tried:
async getUserIdOfPhoneNumber(phone){
this.afs.collection("users", ref => ref.where("phone", "==",phone)).doc().get().toPromise().then(() => {
console.log(res.data())
})
but that brings back undefined because im not providing an id in doc(), I dont want to provide an id because i dont know the id of the collection where the phone number the user entered is equal to the phone value in said doc
removing the doc() function just brings a different mess. data() then doesnt exist
Solution
When you execute a query, there are potentially multiple results. Even when you know there's only one result, the API doesn't know about this, so it returns a list. Your application code will have to deal with this list.
Since I don't see a need to use AngularFire here, this is how you can get a query result in the regular JavaScript SDK (v8 syntax):
firebase.firestore()
.collection("users")
.where("phone", "==",phone)
.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, doc.data());
});
})
Since you know there's at most one result, you can also do:
...
.get().then((querySnapshot) => {
if (!querySnapshot.empty) {
console.log(querySnapshot.docs[0].id, querySnapshot.docs[0].data());
});
})
If you need to do this with AngularFire (i.e. if you want to display the document in the UI), you can use first()
to get the first item from the observable. For more on this, see: https://www.google.com/search?q=angular+observable+get+first+value
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.