Firebase Firestore Query get One result

Viewed 11041

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
    })
}
3 Answers

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

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: john.doe2021@mailinator.com, 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: john.doe2021@mailinator.com, phoneNumber: null, userId: yRARGJOaAbM78MW5OBlVEB3VyKkr, lastSignInOn: Timestamp(seconds=1623663004, nanoseconds=581000000), photoURL: null}

It worked for me. I hope, this will help you.

tried: collection[0] and collection.pop() and nothing works

Those 2 in order means:

  1. collection[0] - access the first element of an array
  2. collection.pop() - pop get's rid of the last element of an array

Maybe 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.

Related