【问题标题】:Firestore/Javascript: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefinedFirestore/Javascript:FirebaseError:使用无效数据调用的函数 DocumentReference.set()。不支持的字段值:未定义
【发布时间】:2020-06-13 09:03:34
【问题描述】:

我一直收到这个错误

创建用户时出错:FirebaseError: Function DocumentReference.set() 用无效数据调用。不支持的字段值:未定义(在 现场糖尿病并发症)

我想我发现了获取所有复选框输入然后将它们存储到数组中的过程的问题。我也知道在将它们存储到 Firestore 之前,我必须使用代码 JSON.stringify()

无论如何,我需要帮助来准确查明问题的原因。因为在过去我成功地将数组存储到firestore中的这个过程正确。

代码如下:

.JS

$('#registerForm').on('submit', async function (e) {
  e.preventDefault();
  var data = {
    email: $('#email').val(), //get the email from Form
    firstName: $('#fname').val(), // get firstName
    lastName: $('#lname').val(), // get lastName
    sex: $('#sex').val(),
    birthDate: new Date($('#bday').val()),
    diabetesType: parseInt($('#dtype').val()),
    weight: parseInt($('#weight').val()),
    height: parseInt($('#height').val()),
  };

  var allergyList = [];
  var cou = i.counter;
  for (c = 0; c <= cou; c++) {
    var allergyField = document.getElementById("allergy" + c).value;
    allergyList.push(allergyField);
    AllergyString = JSON.stringify(allergyList)
  };

  var arrayComplications = [];
  var checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
  for (var i = 0; i < checkboxes.length; i++) {
    JSON.stringify(arrayComplications.push(checkboxes[i].value))
  }

  var passwords = {
    password : $('#password').val(), //get the pass from Form
    cPassword : $('#cpassword').val(), //get the confirmPass from Form
  }

  if( data.email != '' && passwords.password != ''  && passwords.cPassword != '' ){
    if( passwords.password == passwords.cPassword ){
      //create the user
      firebase.auth().createUserWithEmailAndPassword(data.email, passwords.password).then(function(user){setTimeout(function(){
            console.log('uid',user.user.uid);
            usersRef.doc(user.user.uid).set({
              'email': data.email, 'firstName': data.firstName, 
              'lastName': data.lastName, 'allergies': allergyList,
              'sex': data.sex, 'birthDate': firebase.firestore.Timestamp.fromDate(data.birthDate),
              'diabetesType': data.diabetesType, 'diabetesComplication': arrayComplications,
              'weight': data.weight, 'height': data.height, 'firstLogin': true,
         })}, 3000)
          .then(function(){
            console.log("User Information Saved:", user.user.uid);
            window.alert("User Created!");
            window.location.href = "patientDashboard.php"; 
            })               
          })
        .catch(function(error){
          console.log(arrayComplications);
          console.log("Error creating user: ", error);
          console.log("Error creating user: ", user.user.uid);
          window.alert("Error creating user:" + error);
        });

      }
  } 
});

代码如下:

HTML

                                <div class="col-md-6 pl-1">
                                    <div class="form-group">
                                        <label>Diabetes Complication</label>
                                        <br>
                                        <input type="checkbox" name="type" value="No Complications" /><b>No Complications</b>
                                        <br>
                                        <input type="checkbox" name="type" value="Retinopathy" /><b>Retinopathy</b>
                                        <br>
                                        <input type="checkbox" name="type" value="Neuropathy" /><b>Neuropathy</b>
                                        <br>
                                        <input type="checkbox" name="type" value="Nephropathy" /><b>Nephropathy</b>
                                        <br>
                                        <input type="checkbox" name="type" value="Cardiovascular"/><b>Cardiovascular</b>
                                    </div>
                                </div>
                            </div>

注意代码

  var allergyList = [];
  var cou = i.counter;
  for (c = 0; c <= cou; c++) {
    var allergyField = document.getElementById("allergy" + c).value;
    allergyList.push(allergyField);
    AllergyString = JSON.stringify(allergyList)
  };

就是我之前所说的成功完成整个存储过程。

编辑

这是我遇到问题的代码:

  var arrayComplications = [];
  var checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
  for (var i = 0; i < checkboxes.length; i++) {
    JSON.stringify(arrayComplications.push(checkboxes[i].value))
  }

我似乎无法获取复选框值、存储到数组、序列化并将其存储到 firestore。

【问题讨论】:

  • 我不确定 allergyString 是错误的根源。我也想看看生日。无论如何,您可以在“usersRef.doc(user.user.uid).set”之前添加一行,记录您在 set() 中传递的每个值,这样您就可以快速找出未定义的值
  • @GregorioPalamà 问题是复选框我使用过敏代码作为成功的 Firestore 数组存储过程的示例。
  • 这就是为什么我建议打印您传递给 set() 方法的所有值。我怀疑从任何类型的复选框或输入中检索某些内容时存在空值
  • 嗨,你读过道格的回答吗?有帮助吗?如果是这样,请选择它作为正确答案或说明他们的答案有什么问题。
  • @Mayeru 这很有帮助,但如果你有同样的问题,我确实发布了一个答案,我考虑一种解决方法。我已经将其标记为答案欢呼

标签: javascript arrays json google-cloud-firestore


【解决方案1】:

错误消息准确地告诉您出了什么问题。您正在调用 set() 并向其传递一个对象,该对象包含名为 diabetesComplication 的属性的 undefined。这就是这里发生的事情 - 我重新格式化了代码以使其更易于阅读:

usersRef.doc(user.user.uid).set({
    'email': data.email,
    'firstName': data.firstName, 
    'lastName': data.lastName,
    'allergies': allergyList,
    'sex': data.sex,
    'birthDate': firebase.firestore.Timestamp.fromDate(data.birthDate),
    'diabetesType': data.diabetesType,
    'diabetesComplication': arrayComplications,  // this contains undefined
    'weight': data.weight,
    'height': data.height,
    'firstLogin': true,
})

diabetesComplicatation 被分配给arrayComplicatation 的行 - 某处有一个未定义的值。 Firestore 根本不接受未定义的值,因为没有等效的表示。您必须调试代码以确定未定义值的来源,或者确保在传递给 set() 之前将它们删除。

也许您可以在进入arrayComplications 之前检查来自checkboxes[i].valuefor 循环中的未定义值。 (而且我不确定您为什么要尝试对推送的结果进行字符串化。这似乎在任何地方都没有效果。)这取决于您进行调试,因为我们在这里看不到所有值。

【讨论】:

    【解决方案2】:

    我还找到了另一个解决方案,我将输入类型更改为复选框而不是下拉菜单。

    HTML

                                    <div class="col-md-6 pl-1">
                                        <div class="form-group">
                                            <label>Diabetes Complication</label>
                                            <br>
                                            <input type="checkbox" name="type" value="No Complications" /><b>No Complications</b>
                                            <br>
                                            <input type="checkbox" name="type" value="Diabetic Retinopathy" /><b>Retinopathy</b>
                                            <br>
                                            <input type="checkbox" name="type" value="Diabetic Neuropathy" /><b>Neuropathy</b>
                                            <br>
                                            <input type="checkbox" name="type" value="Diabetic Nephropathy" /><b>Nephropathy</b>
                                            <br>
                                            <input type="checkbox" name="type" value="Diabetic Cardiovascular"/><b>Cardiovascular</b>
                                            <br>
                                        </div>
                                    </div>
    

    然后对于脚本,我得到检查的值并将它们存储在一个数组中并序列化它们以用于 Firestore 存储。

    var arrayComplications = [];
    var checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
    for (var i = 0; i < checkboxes.length; i++) {
      JSON.stringify(arrayComplications.push(checkboxes[i].value));
    }
    

    希望这对任何人都有帮助

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 2019-12-07
      • 2019-04-25
      • 2019-12-20
      • 2020-04-24
      • 2021-08-20
      • 2018-08-11
      相关资源
      最近更新 更多