0

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:

  1. Whenever a new form is added, the function triggers ✅
  2. Read the filler data and check if there's a phone number, I have used typeof to check if the field exists in Firestore, If not. Set the filler's phone number to 100. But if exists, update it with the newly submitted forms field which is phoneID

What is not working:

  1. this code works till the console.log("new form" + newValue) line and i don't get a print for neither of the following if statement. There's no OP 1 executed or OP 2 executed in the logs.
    1. there's a phone field with value of 0 in my database generated randomly.

I'm new to JS and your help is appreciated

1
  • What does the log say in the Firebase console for Cloud Functions? If there's a problem, it will appear there. Commented Mar 9, 2019 at 19:13

1 Answer 1

1

Looks like your "userRef.get()" promise is somehow failing. You could add a catch at the end and do a console log in there to see what the error is, like:

return userRef.get().then(
   ...
)
.catch(
  error => console.log('The error is:', error)
);