Skip to content

Instantly share code, notes, and snippets.

@bcnzer
Created February 23, 2020 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bcnzer/269969c38443a89be831c07adbe934c4 to your computer and use it in GitHub Desktop.
Save bcnzer/269969c38443a89be831c07adbe934c4 to your computer and use it in GitHub Desktop.
Example of how to perform a get, add and update using Cloud Firestore in a Function
// Make sure to use firebase-admin and to initialize the app
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
// Example of how I'm GETTING all the records in a collection AND using
// the ID from the path of the document that triggered this function
exports.getLessonsAsync = functions.firestore
.document('organizations/{organizationId}/lessons/{lessonId}')
.onWrite(async function(change, context) {
const result = await admin
.firestore()
.collection('organizations')
.doc(context.params.organizationId)
.collection('lessons')
.get()
result.forEach((doc) => {
console.log(doc.id, '=>', doc.data())
})
})
// Example of how I'm getting ADDING a record to the collection AND using
// the ID from the path of the document that triggered this function
exports.addLessonAsync = functions.firestore
.document('organizations/{organizationId}/lessons/{lessonId}')
.onWrite(async function(change, context) {
await admin
.firestore()
.collection('organizations')
.doc(context.params.organizationId)
.collection('lessons')
.add({
name: 'Rock band project'
})
})
// Example of how I'm getting UPDATING a record to the collection AND using
// the ID from the path of the document that triggered this function
exports.updateLessonAsync = functions.firestore
.document('organizations/{organizationId}/lessons/{lessonId}')
.onWrite(async function(change, context) {
await admin
.firestore()
.collection('organizations')
.doc(context.params.organizationId)
.collection('lessons')
.doc(context.params.lessonId)
.update({
name: 'Rock band project v2'
})
})
// Example of how I'm determining what actually happened to a document
// by using the before and after data methods
exports.howToCheckStatusOfRecordUsingOnWrite = functions.firestore
.document('organizations/{organizationId}/lessons/{lessonId}')
.onWrite(async function(change, context) {
// With onWrite you get the before and after so you can figure out if it was added, updated or deleted
const originalLesson = change.before.data()
const updatedLesson = change.after.data()
if (!originalLesson) {
console.log('New lesson so ignore')
} else if (!updatedLesson) {
console.log('Deleted lesson')
} else {
console.log('Updated lesson')
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment