简体   繁体   中英

how write correctly a cloud functions v9 with getFirestore() inside an onRequest function?

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)
    })
  })
})

this function is returning me an empty array, while this function on normal client call get almost 300 files.

What i'm doing wrong? Do i need to use query / where in an different format?

The V9 SDK is better used from clients such as mobile and web applications. Since you are building Cloud Functions that will interact with Firestore, you should instead use the Admin SDK. This SDK can be easily initialized when running inside Firebase services like Cloud Functions.

You would only need to make minimal changes to your code, as the Firestore instance supports the syntax you have been using:

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
  });

You can also check the API reference for the relevant methods likewhere() and relevant examples. For a complete sample, you can check out the code inside the quickstart repo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM