【发布时间】:2019-03-09 18:28:58
【问题描述】:
我添加了一个触发器,该触发器在将新记录添加到指定路径时起作用。
我的代码:
exports.modifyNewForm = functions.firestore
.document('users/{userId}/form_fillers/{filler}/forms/{form_id}')
.onCreate((snap, context) => {
const newValue = snap.data();
const first_name = "James";
const last_name = "Alex";
const newPhone = 100;
// Parameters
const userId = context.params.userId;
const filler_1 = context.params.filler;
const form_id = context.params.form_id;
const userRef = admin.firestore().collection('users').doc(userId).collection("form_fillers").doc(filler_1);
console.log("new form" + newValue)
return userRef.get().then(parentSnap => {
const user = parentSnap.data();
const phone = user.phone
if(typeof phone === "undefined") {
console.log("OP 1 executed");
return admin.firestore().collection('users').doc(userId).collection('form_fillers').doc(filler_1).set({first_name:first_name, last_name:last_name,phone:newPhone}, {merge: true}).then(writeResult => {
console.log("New write: " + writeResult);
});
} else {
console.log("OP 2 executed");
return admin.firestore().collection('users').doc(userId).collection('form_fillers').doc(filler_1).set({first_name:first_name, last_name:last_name,phone: user.phoneID}, {merge: true}).then(writeResult => {
console.log("New write: " + writeResult);
});
}
});
});
好的,在这段代码中,我正在尝试实现这一点:
- 每当添加新表单时,函数都会触发 ✅
- 读取
filler数据并检查是否有电话号码,我使用typeof检查Firestore中是否存在该字段,如果没有。将filler的电话号码设置为100。但如果存在,请使用新提交的表单字段phoneID对其进行更新
什么不工作:
- 这段代码一直有效到
console.log("new form" + newValue)行,我没有得到以下if语句的打印。日志中没有OP 1 executed或OP 2 executed。- 在我的数据库中随机生成了一个值为
0的phone字段。
- 在我的数据库中随机生成了一个值为
我是 JS 新手,非常感谢您的帮助
【问题讨论】:
-
Cloud Functions 的 Firebase 控制台中的日志说明了什么?如果有问题,就会出现在那里。
标签: node.js firebase google-cloud-firestore google-cloud-functions