Reputation: 11588
I'm looking for the best way to:
1. query for one single result, or
2. extract the first result from the query
tried: collection[0]
and collection.pop()
or collection.shift()
and nothing works
I really don't like the code i'm using, but it works...
export const findUserByEmail = email => {
return firestore()
.collection('users')
.where('email', '==', email.toLowerCase())
.get()
.then(collection => {
console.log(collection)
let user
collection.forEach(doc => user = doc.data())
return user
})
}
Upvotes: 24
Views: 18884
Reputation: 404
tried:
collection[0]
andcollection.pop()
and nothing works
Those 2 in order means:
collection[0]
- access the first element of an arraycollection.pop()
- pop gets rid of the last
element of an arrayMaybe based on your code logic, you should try: collection[0].data()
; as by using collection[0]
you access the first element, but from your existing code you need to call .data()
to extract it.
forEach
does simply access to the whole content of collection
.
Whilst collection.pop()
is just not the proper tool for the job in this case.
Upvotes: -1
Reputation: 6135
Firestore with Flutter solution:
await FirebaseFirestore.instance
.collection('users')
.where('userId', isEqualTo: loggedInUserId)
.get()
.then((querySnapshot) {
List listData = querySnapshot.docs.toList().map((item) {
// to fetch list of all documents information
return item.data();
}).toList();
if (querySnapshot.docs.length > 0) {
// to fetch first document information
_mappedUserInfo = querySnapshot.docs[0].data();
}
print("listData: ${listData.toString()}");
print("_mappedUserInfo: ${_mappedUserInfo.toString()}");
}).catchError((e) {
print('data error: $e');
});
Result:
Fetched List of documents:
listData: [{name: null, addedOn: Timestamp(seconds=1623663004, nanoseconds=581000000), email: [email protected], phoneNumber: null, userId: yRARGJOaAbM78MW5OBlVEB3VyKkr, lastSignInOn: Timestamp(seconds=1623663004, nanoseconds=581000000), photoURL: null}]
Fetched single document:
_mappedUserInfo: {name: null, addedOn: Timestamp(seconds=1623663004, nanoseconds=581000000), email: [email protected], phoneNumber: null, userId: yRARGJOaAbM78MW5OBlVEB3VyKkr, lastSignInOn: Timestamp(seconds=1623663004, nanoseconds=581000000), photoURL: null}
It worked for me. I hope, this will help you.
Upvotes: 1
Reputation: 4081
Your query returns a QuerySnapshot
(see docs). You can access the docs as an array via the docs
property; each doc has a data()
method:
export const findUserByEmail = email => {
return firestore()
.collection('users')
.where('email', '==', email.toLowerCase())
.get()
.then(querySnapshot => {
if(!querySnapshot.empty) {
const user = querySnapshot.docs[0].data()
// rest of your code
}
})
}
Upvotes: 46