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")
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With