Blue
Blue

Reputation: 1448

Firestore access using Cloud Functions event

I'm struggling with a few syntax issues

exports.deleteProject = functions.firestore.document('{userID}/projects/easy/{projectID}').onDelete(event => {

inside the functions I have

console.log(event)

which outputs

 { data: 
   DocumentSnapshot {
     _ref: DocumentReference { _firestore: [Object], _referencePath: [Object] },
     _fieldsProto: undefined,
     _readTime: undefined,
     _createTime: undefined,
     _updateTime: undefined },
  eventId: 'd4079c38-2dc1-44e2-924d-fa27c3a95f8b-0',
  eventType: 'providers/cloud.firestore/eventTypes/document.delete',
  notSupported: {},
  params: 
   { userID: 'xxxxxxxxxxxxxx',
     projectID: 'dddddddddddd' },
  resource: 'projects/nnnnnnnnn/databases/(default)/documents/xxxxxxxxxxxxxx/projects/easy/dddddddddddd',
  timestamp: '2017-11-11T04:41:16.712975Z' }

The problem I have is I can't seem to figure out the syntax to reference the database (and subsequently another collection/document path) itself or the different elements that appear when I print out event.

Any help would be appreciated

Upvotes: 3

Views: 866

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

When you receive a Firestore event in Cloud Functions, it's an object of type Event<DeltaDocumentSnapshot>, which means event.data is of type DeltaDocumentSnapshot. With this, you can access the entire database using the received event via event.data.ref.firestore. This gives you a Firestore object that you can use to access collections and documents within that instance of Firestore. For example:

const firestore = event.data.ref.firestore
const docref = firestore.doc('collection/doc')

Also, you can use the Admin SDK (with its Firestore API) to access Firestore directly from any Cloud Function without a Firestore event.

Upvotes: 3

Related Questions