How to access Cloud Firestore from Google Sheets?

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.


function writeDataToFirestore() {
  var projectId = "XXXXXXXX";
  var key = "-----BEGIN PRIVATE KEY-----\nXXXXXXXXXX\n-----END PRIVATE KEY-----\n";
  var email = "[email protected]";
  var firestore = FirestoreApp.getFirestore(email, key, projectId);
  const data = {
    "name": "test!"
  }
  firestore.createDocument("FirstCollection", data)
}