使用云功能将数据写入Firestore

问题描述 投票:0回答:1

我添加了一个触发器,只要将新记录添加到指定路径,该触发器就会起作用。

我的代码:

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);
    });

        } 
    }); 

});

好的,在这段代码中,我试图实现这个目的:

  1. 每当添加新表单时,该函数都会触发✅
  2. 阅读filler数据并检查是否有电话号码,我使用typeof检查Firestore中是否存在该字段,如果没有。将filler的电话号码设置为100。但如果存在,请使用新提交的表单字段phoneID更新它

什么不起作用:

  1. 这段代码一直工作到console.log("new form" + newValue)线,我没有得到以下if声明的打印。日志中没有OP 1 executedOP 2 executed。 在我的数据库中随机生成一个phone字段,其值为0

我是JS的新手,感谢您的帮助

node.js firebase google-cloud-firestore google-cloud-functions
1个回答
1
投票

看起来你的“userRef.get()”承诺在某种程度上失败了。您可以在最后添加一个catch并在其中执行控制台日志以查看错误,例如:

return userRef.get().then(
   ...
)
.catch(
  error => console.log('The error is:', error)
);
© www.soinside.com 2019 - 2024. All rights reserved.