I am testing Firestore triggered Firebase Cloud Function locally in Node using Firebase Functions Shell.
When working with a onWrite trigger and passing a new document by calling updateMonth({foo:'new'}) from the functions shell, I can't get a reference to the new document.
exports.updateMonth = functions.firestore
.document('users/{userId}').onWrite((change, context) => {
const document = change.after.exists ? change.after.data() : null;
console.log("change.after.exists", change.after.exists)
console.log("change.before.exists", change.before.exists)
const oldDocument = change.before.data();
console.log("Old:",oldDocument)
return true
})
When calling with both a before and after to emulate a document update updateMonth({before:{foo:'old'},after:{foo:'new'}}) it works as expected.
However, when called with just updateMonth({foo:'new'}), both before and after documents don't seem to exist :
i functions: Preparing to emulate functions.
Warning: You're using Node.js v8.4.0 but Google Cloud Functions only supports v6.11.5.
+ functions: hi
+ functions: helloWorld
+ functions: updateMonth
firebase > updateMonth({before:{foo:'old'},after:{foo:'new'}})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: change.after.exists true
info: change.before.exists true
info: Old: { foo: 'old' }
info: Execution took 20 ms, user function completed successfully
firebase > updateMonth({foo:'new'})
'Successfully invoked function.'
firebase > info: User function triggered, starting execution
info: change.after.exists false
change.before.exists false
Old: undefined
Execution took 2 ms, user function completed successfully
I'm not sure how I can get a reference to the new document being created. I would expect the change.after.exists to be true in that case.
beforeandafterdocuments should always exist. onWrite will trigger with any change (and you have to be care to check what happened). What are you trying to accomplish here? - Doug Stevenson