Firebase/Firestore 数据不是函数

Tra*_*rax 2 firebase google-cloud-functions google-cloud-firestore

我正在尝试使用 firebase 云函数内的 where 子句进行简单的 firestore 查询,但我得到了foo.data is not a function.

exports.uploadList = functions.https.onRequest(async (req, res) => {
 try {
    let foo = await db.collection('users').where('appToken', '==', 'xxxx').get()
    if (foo) {
      return res.status(200).send({ foo: foo.data() })
    }
  } catch (error) {
    return res.status(500).send(error)
  }
})
Run Code Online (Sandbox Code Playgroud)

我得到的响应是一个空对象{},如果删除 try/catch 块,我可以在云函数日志中看到错误foo.data is not a function

我读到这where()是可选的,所以也尝试过db.collection('users').get(),结果相同。

我可以使用查询db.collection().doc().get(),它工作正常,但无法通过字段值查找文档。set并且update工作也很好。

Dou*_*son 5

您编写的这段代码:

db.collection('users').where('appToken', '==', 'xxxx').get()
Run Code Online (Sandbox Code Playgroud)

返回一个使用QuerySnapshot类型对象(而不是DocumentSnapshot )解析的承诺。正如您从链接的 API 文档中看到的,QuerySnapshot 没有data()像 DocumentSnapshot 那样的方法。这是因为 SDK 事先并不知道结果集中有多少文档。因此,您必须迭代结果。一种方法是使用QuerySnapshot 上的属性,它只是与查询约束匹配的QueryDocumentSnapshotsdocs数组。或者用它的方法。forEach

文档中有很多示例。