Firebase Firestore 查询得到一个结果

And*_*dez 11 javascript firebase google-cloud-firestore

我正在寻找最佳方法:
1. 查询单个结果,或
2. 从查询中提取第一个结果

尝试过:collection[0]and collection.pop()or collection.shift()and 没有任何效果

我真的不喜欢我正在使用的代码,但它有效......

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
    })
}
Run Code Online (Sandbox Code Playgroud)

Aja*_*les 23

您的查询返回一个QuerySnapshot请参阅文档)。您可以通过docs属性以数组的形式访问文档;每个文档都有一个data()方法:

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 
      }
    })
}
Run Code Online (Sandbox Code Playgroud)