Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Cloud Firestore from Google Sheets?

I am trying to access Cloud Firestore database from Google sheet with the help of FirestoreGoogleAppsScript example, but as explained in the 5th point I have downloaded the file but not getting where to update the client_email, private_key and project_id in the project. So kindly guide me to move forward.

When you press "Create," your browser will download a .json file with your private key (private_key), service account email (client_email), and project ID (project_id). Copy these values into your Google Apps Script — you'll need them to authenticate with Firestore.

with a demo Code.gs

function myFunction() {
  projectid: "xxx";
  key: "-----BEGIN PRIVATE KEY-----\nPrivateKeyHere\n-----END PRIVATE KEY-----\n";
  email: "[email protected]";
  
  var firestore = FirestoreApp.getFirestore(email, key, projectId);
}

error

ReferenceError: "email" is not defined. (line 7, file "Code")
like image 487
Tushar Rai Avatar asked Apr 02 '19 10:04

Tushar Rai


People also ask

How do I access data from firestore database?

Reading data from Firestore There are two ways for retrieving data, which is stored in Cloud Firestore. Calling a method to get the data. Setting a listener for receiving data changes events. We send an initial snapshot of the data, and then another snapshot is sent when the document changes.


1 Answers

You have to do as follows, for example in a simple function that fetches a collection:

function fecthFirstCollectionDocs() {

  var email = "[email protected]";
  var key = "-----BEGIN PRIVATE KEY-----\your key here\n-----END PRIVATE KEY-----\n";
  var projectId = "zzzzzzzzz";

  var firestore = FirestoreApp.getFirestore(email, key, projectId);

  const allDocuments = firestore.query("FirstCollection").execute();
  Logger.log(JSON.parse(allDocuments));

}

The value of key is obtained by creating a service account, as explained in the Library documentation: https://github.com/grahamearley/FirestoreGoogleAppsScript#creating-a-service-account. It's quite easy, just follow the instructions.

You have to copy only the part between -----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----\n from the .json file.


Edited following you comment of 9 April:

To solve the

ReferenceError: "email" is not defined. (line 7, file "Code") 

error you should correctly declare the variables you pass to the getFirestore() method, as shown in the code of my answer, and as follows:

instead of doing

  projectid: "fir-79c39";

you should do

  var projectid = "fir-79c39";

You declare a variable named projectid that you use in the getFirestore() method. The same for key and email.

like image 122
Renaud Tarnec Avatar answered Nov 24 '22 07:11

Renaud Tarnec