Firestore / Javascript:FirebaseError:函数DocumentReference.set()用无效数据调用。不支持的字段值:未定义

时间:2020-02-29 13:24:07

标签: javascript arrays json google-cloud-firestore

我不断收到此错误

创建用户时出错:FirebaseError:函数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中。

2 个答案:

答案 0 :(得分:1)

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

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()之前确保将其删除。

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

答案 1 :(得分:0)

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

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

希望这对任何人都有帮助

相关问题