Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error

Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication)

After some investigation, I realized that the issue stems from the approach of collecting checkbox inputs and storing them in an array. I understand now that I need to use JSON.stringify() before saving them in firestore.

However, I am struggling to pinpoint the exact cause of the problem. It's perplexing because I've previously succeeded in storing arrays in firestore using a similar process.

Below is the code snippet:

JavaScript:

$('#registerForm').on('submit', async function (e) {
  e.preventDefault();
  var data = {
    email: $('#email').val(),
    firstName: $('#fname').val(),
    lastName: $('#lname').val(),
    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(), 
    cPassword : $('#cpassword').val() 
  };

  if( data.email != '' && passwords.password != ''  && passwords.cPassword != '' ){
    if( passwords.password == passwords.cPassword ) {
      // Code to create user omitted for brevity
    }
  } 
});

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>

The section of code where I encounter issues with includes:

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

I am struggling to extract the values of the checkboxes, save them into an array, serialize it, and store it in firestore.

Answer №1

The error message clearly explains the issue at hand. When you call set() with an object that has a property named diabetesComplication containing undefined, Firestore rejects it. Here's a clearer code format for reference:

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,  // contains undefined value
    'weight': data.weight,
    'height': data.height,
    'firstLogin': true,
})

In the line where diabetesComplicatation is set to arrayComplicatation, there seems to be an undefined value present. Firestore does not accept undefined values due to their lack of representation. You'll need to trace and eliminate these undefined values in your code before passing them to set().

You might want to double-check for undefined values within your for loop when extracting from checkboxes[i].value before adding them into arrayComplications. Also, the attempt to stringify the push results appears unnecessary. Debugging this issue is essential since we don't have full visibility into all variables.

Answer №2

I discovered a different approach that worked for me - I switched my input type from dropdowns to checkboxes.

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>

For the script, I captured the checked values and stored them in an array which was then serialized for firestore storage.

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

Hopefully this solution can be useful to others as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

typescript scrolling location

In my Angular UI code, I have a component class that includes the following structure: app.component.html //... <div class="banner"> <p-dialog [(visible)]="displayCOI" styleClass="coiDialog" [contentStyle]=" ...

Is there a way to create a nested object literal that will return the length of

I am working with JSON data that includes different locations (sucursales) and cars for each location. How can I write a function to calculate the total number of cars across all locations? [{"sucursal": "Quilmes", "direccion&q ...

Is there a way to prevent users from selecting dates and times prior to today, as well as blocking out the hours of 9:00am

Users are required to select a date within the range of today's date and one month in the future, and a time between 9:00am and 9:00pm. How can I implement validation to ensure this? <div class="row"> <div class="col"> <label cl ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

Retrieve JSON data using the jQuery Form plugin

Currently, I am utilizing the jquery form plugin to send ajax forms to the server. Upon checking for errors on the server, a JSON object is returned with multiple fields. The JSON response takes the following format: { "error1" : "true", "error2" : "fals ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...

Menu options submerged beneath the surface of a concealed container with overflow property

Attempting to enhance the ui-grid by adding more options to each row using the "3 dots" approach. However, encountered an issue where the dropdown menu extends beyond the screen due to the use of position: absolute. Unable to switch to position: relative b ...

Utilizing AngularJS $anchorScroll for navigating to an anchor tag on a different page

On my AngularJS Home Page, I am trying to scroll to an anchor tag on another page. Both pages are loaded as partial html files into the ng-view component based on the URL. When I start the server, the home page loads and then I need to navigate to the FAQ ...

JavaScript/DOM - What sets apart a "CSS Selector" from an attribute?

When it comes to excluding declarative event handlers: <a href='#' onclick=<handler> ... /> Is there a significant difference between an Attribute and a CSS Selector? For example, if I define my own attribute: <a href='#&a ...

Issue: There is no specified method of transportation established

I'm facing an issue while trying to create an Outlook calendar event from my application using Express.js. The error message I am receiving is [Error:No transport method defined], and eventually, the response returns as 200 success after approximately ...

Create a feature that dynamically loads JSON Data onto a TableView in iOS as the user scrolls

I have developed an application that utilizes JSON data from web services. My web services consist of three pages, and when I add data to the tableview, it fills the first page. However, when I scroll the table view to the second page, the data from the fi ...

NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality. Everything works smoothly when running the page with npm run dev. However, after ex ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...

Performing pandas.json_normalize on nested JSON data without a consistent record_path

Currently, I am facing a challenge in converting a large JSON file to CSV format. The specific issue arises when attempting to sort data on the Spreadsheet because the field required for sorting is consolidated into one cell during the conversion process. ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

Stop users from repeating an action

We are encountering challenges with users repeating a specific action, even though we have measures in place to prevent it. Here is an overview of our current approach: Client side: The button becomes disabled after one click. Server side: We use a key h ...

Issue with Symfony2 JMS Serializer JSON_ constant error

An unexpected error occurred while trying to install a project on the production server. The PHP Fatal error states: 'Uncaught exception 'JMS\Serializer\Exception\InvalidArgumentException' with message 'Expected either an ...