我的Firestore中有2个集合,'students'和'student_history'。每次在'students'中创建或更新文档时,我想使用云函数获取它,添加一个名为{" created At": "时间戳;}或{"更新时间;: "timestamp"},并将这个新文档写入'student_history'。
以下是我为相同目的编写的firebase云函数:
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);
});
理想情况下,我希望能够添加一个字段,如{"Created At": &;timestamp&;}到'values',然后将其添加到'student_history'。实现这一目标的正确方法是什么,或者对于整个场景是否有更好/不同的解决方案?谢谢你。
解决方案如下:
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()});
});
修复是使用'…"操作符
。学分:tylim