How can I trigger a function on any document change in any collection in Firestore? I want to manage createdAt
and updatedAt
timestamps. I have many collections and don't want to have to register the trigger for each independently. At that point I might as well just create wrapper functions for add
, set
, and update
.
How can I register a callback that fires when any document is modified?
EDIT:
At this time (2019-08-22), I decided to just create a wrapper function to implement this functionality. The accepted answer does not maintain schema-less-ness. Based on this article, I created this upset
function which manages timestamps and avoids "document does not exist" errors:
const { firestore: { FieldValue } } = require('firebase-admin')
module.exports = async function upset (doc, data = {}) {
const time = FieldValue.serverTimestamp()
const update = { updatedAt: time }
const updated = { ...data, ...update }
try {
const snapshot = await doc.get()
if (snapshot.exists) {
return doc.update(updated)
} else {
const create = { createdAt: time }
const created = { ...updated, ...create }
return doc.set(created)
}
} catch (error) {
throw error
}
}