Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pglazkov/46087c59a6faec539d2676e75ddba3e4 to your computer and use it in GitHub Desktop.
Save pglazkov/46087c59a6faec539d2676e75ddba3e4 to your computer and use it in GitHub Desktop.
Firestore cloud function that maintains a document field that contains number of items in a collection
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const db = admin.firestore();
exports.updateMyCollectionCount = functions.firestore
.document(`users/{userId}/my-collection/{itemId}`)
.onWrite(event => {
const isUpdate = event.data.exists && event.data.previous.exists;
if (isUpdate) {
console.log('Skipping because it is an update operation.');
return null;
}
const userRef = db
.collection('users')
.doc(event.params.userId);
return db.runTransaction(t => {
return t.get(userRef).then(userDoc => {
return userDoc.ref.collection('my-collection').get().then(collectionSnapshot => {
const newCount = collectionSnapshot.size;
const updateData = {
'my-collection-count': newCount
};
// If the `user` document alread exists, we need to use `update` operation,
// otherwise, if we use `set`, then all the data on the `user` document
// will be overriden. On the other hand, if the `user` document doesn't
// exist, we cannot use `update` because it requires the document to exist.
if (userDoc.exists) {
t.update(userRef, updateData);
}
else {
t.set(userRef, updateData);
}
console.log('Count updated successfully. New count is: ' + newCount);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment