Firebase Firestore Query get One result

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

Answers (3)

SpeederX
SpeederX

Reputation: 404

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

Upvotes: -1

Kamlesh
Kamlesh

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

charles-allen
charles-allen

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

Related Questions