skip to Main Content

Hello I am running a small script that I want to run locally since max timeout of firebase functions is 9 minutes and that is not enough for me (I have to run a large scale update on data types).

So the code is basically:

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

db.collection('users')
  .get()
  .then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
      // update doc
    });
  });

But querySnapshot.docs has 0 elements. I checked the same code in functions and it works properly. What could be the cause of this? If this is not possible are there any workarounds where I can bypass timeout using cloud functions?

Firebase is initialized correctly both in my machine and directory. I tried a clean initialized directory too. Same code when passed to an firebase function endpoint and ran once works perfectly fine.

2

Answers


  1. Chosen as BEST ANSWER

    When I initialized like this everything seemed to work fine. The reason why applicationDefault doesn't work is I think because doc says it works in google environments.

    const admin = require('firebase-admin');
    var serviceAccount = require('path/to/key.json')
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount)
    });
    

  2. If you run a script written with the Admin SDK locally on your computer you need to initialize the SDK with an exported service account key file as explained in the doc.

    The doc details how to:

    1. Generate a private key file in JSON format from the Firebase console
    2. Set an environment variable to the file path of the JSON file that contains your service account key.

    Then you can do as follows:

    const admin = require('firebase-admin');
    admin.initializeApp({
        credential: applicationDefault()
    });
    
    const db = admin.firestore();
    
    db.collection('users')
        .get()
        .then(querySnapshot => {
            return Promise.all(querySnapshot.docs.map(doc => doc.ref.update( {...} ))):
        })
        .then(() => {...})
        .catch(...)
    

    Note that to update several docs within a loop via the asynchronous update() method you’ll need to use Promise.all(), as shown above.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search