I have 2 collections in my Firestore, 'students' and 'student_history'. Every time a document is created or updated in 'students', I want to fetch it using a cloud function, add a field called {"Created At" : "timestamp"} or {"Updated At" : "timestamp"} to the document and write this new document into 'student_history'.
Here are the firebase cloud functions that I have managed to write for the same :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
exports.onUserCreate = functions.firestore.
document("students/{student_id}").onCreate(
async (snap, context) => {
const values = snap.data(); //line 8
console.log(values);
console.log(typeof values);
await db.collection("student_history").add(values);
});
exports.onUserUpdate = functions.firestore.
document("students/{student_id}").onUpdate(
async (snap, context) => {
const values = snap.after.data();
console.log(values);
console.log(typeof values);
await db.collection("student_history").add(values);
});
Ideally, I want to be able to append a field like {"Created At" : "timestamp"} to 'values' before adding it to 'student_history'. What would be the correct way to achieve this or is there a better/different solution for the entire scenario? Thank you.
Here is the solution :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const FieldValue = admin.firestore.FieldValue;
admin.initializeApp();
const db = admin.firestore();
exports.onUserCreate = functions.firestore.
document("students/{student_id}").onCreate(
async (snap, context) => {
const values = snap.data();
console.log(values);
console.log(typeof values);
return db.collection("student_history").add({...values, createdAt:FieldValue.serverTimestamp()});
});
exports.onUserUpdate = functions.firestore.
document("students/{student_i
d}").onUpdate(
async (snap, context) => {
const values = snap.after.data();
console.log(values);
console.log(typeof values);
return db.collection("student_history").update({...values, updatedAt:FieldValue.serverTimestamp()});
});
The fix was to use '...' operator.
Credits: tylim