I have added a trigger which works whenever a new record is added to a specified path.
My code:
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);
});
}
});
});
Ok so in this code, I'm trying to achieve this:
- Whenever a new form is added, the function triggers ✅
- Read the
filler
data and check if there's a phone number, I have usedtypeof
to check if the field exists in Firestore, If not. Set thefiller
's phone number to100
. But if exists, update it with the newly submitted forms field which isphoneID
What is not working:
- this code works till the
console.log("new form" + newValue)
line and i don't get a print for neither of the followingif
statement. There's noOP 1 executed
orOP 2 executed
in the logs.- there's a
phone
field with value of0
in my database generated randomly.
- there's a
I'm new to JS and your help is appreciated