Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    })
}
like image 357
André Alçada Padez Avatar asked Oct 16 '19 07:10

André Alçada Padez


1 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 
      }
    })
}
like image 51
charles-allen Avatar answered Sep 28 '22 01:09

charles-allen