【问题标题】:how write correctly a cloud functions v9 with getFirestore() inside an onRequest function?如何在 onRequest 函数中使用 getFirestore() 正确编写云函数 v9?
【发布时间】:2022-01-18 06:50:19
【问题描述】:
exports.testGetTransactions = functions.region('southamerica-east1').runWith({
  timeoutSeconds: 60,
  memory: '8GB',
}).https.onRequest((request, response) => {
  cors(request, response, () => {
    functions.logger.log('body', request)
    functions.logger.log('request body', request.body)
    let array = []
    getFirestore().collection('transactions').where('purchaseEpoch', '>', 1639842778924).where('purchaseEpoch', '<', 1642434778924).orderBy('purchaseEpoch', 'desc').limit(4000).get().then((querySnapshot) => {
      functions.logger.log('array', querySnapshot)
      querySnapshot.forEach((item, i) => {
        array.push(item.data())
      })
      functions.logger.log('array final', array)
      return response.status(200).send(array)
    }).catch((error) => {
      return response.status(400).send(error)
    })
  })
})

这个函数返回一个空数组,而这个函数在正常的客户端调用中得到了近 300 个文件。

我做错了什么?我需要使用不同格式的查询 / where 吗?

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    V9 SDK 是 better 用于移动和 Web 应用程序等客户端。由于您正在构建将与 Firestore 交互的 Cloud Functions,因此您应该改用 Admin SDK。当在 Cloud Functions 等 Firebase 服务中运行时,此 SDK 可以轻松 initialized

    您只需对代码进行少量更改,因为 Firestore 实例支持您一直使用的语法:

    const admin = require('firebase-admin');
    admin.initializeApp();
    
    const db = admin.firestore(); // Firestore instance from admin SDK
    
    exports.writeToFirestore = functions.firestore
      .document('some/doc')
      .onWrite((change, context) => {
        db.doc('some/otherdoc').set({ ... }); //Using the Firestore instance to update a document
      });
    

    您还可以查看 API 参考中的相关方法,例如 where() 和相关示例。如需完整示例,您可以查看quickstart repo 中的code

    【讨论】:

    • @eeerrrttt 您是否能够测试此信息是否对您的功能有用?以防其他用户感兴趣
    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 2021-06-10
    • 2018-05-14
    • 1970-01-01
    • 2022-01-15
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多