Skip to content

Instantly share code, notes, and snippets.

@rayfarer
Created April 1, 2018 15:47
Show Gist options
  • Save rayfarer/c30496baf706c08ed0bcea5dbbe2347f to your computer and use it in GitHub Desktop.
Save rayfarer/c30496baf706c08ed0bcea5dbbe2347f to your computer and use it in GitHub Desktop.
Add Timestamp When Document Created Firestore
/*
Using Cloud Functions, here's what I've come up with for anyone who wants to
add a timestamp field in a Firestore document. You need to have the Firebase Admin SDK installed in
addition to the general setup for Cloud Functions as detailed in the Firebase documentation.
*/
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Use a wildcard to identify the document if you are unsure of its ID
exports.addServerTimestamp = functions.firestore
.document('collection/{itemID}')
.onCreate(event => {
const itemID = String(event.params.itemID)
const doc = admin.firestore().collection('collection').doc(itemID);
doc.set({
timeStamp: admin.firestore.FieldValue.serverTimestamp()},
{merge:true}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment