Storing a boolean value in MongoDB as a string

const myObject = { school: true, address: false };     
const myArray = [];
        
myArray.push(myObject);

updateSchool(myArray);

function updateSchool(thisSchool) {
  $.ajax
    ({
    type: "POST",
    url: '/update_school',
    data: {
        school: thisSchool, 
    },
   }
   })

within App.js:

app.post('/update_school', function(request, response) {
   ......
    db.collection("School").updateOne({_id: request.session.username},{$set: 
    {School:request.body.school}}, function(err, result){
    ...... }
    }

When storing boolean values in MongoDB, they are stored as strings like

[{school:"true", address:"false"}]

Can anyone assist me with the process of storing Boolean values in MongoDB properly? Thank you.

Answer №1

When you provide an object as data in $.ajax(), it will be converted to a URL encoded string (

application/x-www-form-urlencoded
) which does not support boolean data type according to the documentation found here:

When data is an object, jQuery creates the data string from the object's key/value pairs unless the processData option is set to false. For instance, { a: "bc", d: "e,f" } becomes the string "a=bc&d=e%2Cf"

To properly save boolean values, manual parsing is necessary on the server side or sending the payload as JSON (application/json). Below is how you can achieve the latter using jquery:

function writeObj(obj) {
  document.write('<pre>' + JSON.stringify(obj, null, 4) + '</pre>');
}

function updateSchool(thisSchool) {
  $.ajax({
      type: "POST",
      // url: '/update_school',
      url: 'https://httpbin.org/anything',
      contentType: 'application/json',
      data: JSON.stringify({
        school: thisSchool,
      }),
    })
    .done(writeObj)
    .fail(writeObj);
}

var myobj = {
  school: true,
  address: false
};
var myArray = [];
myArray.push(myobj);
updateSchool(myArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

When running `npm start`, if you encounter an error message that says `npm ERR`,

When attempting to run this JS project on my Mac using this JS project, I encountered an npm error after typing npm start: https://i.sstatic.net/o2UZj.png Despite searching various websites for a solution, I have already included these lines in my packag ...

The Raycaster in Three.js seems to be malfunctioning as the IntersectObjects method is providing intersection distances that are inconsistent and illogical

In my latest three.js project, I am developing a simple game where the user takes control of a spaceship named playerModel (a Mesh object with a basic BoxGeometry). The objective is to navigate through space while avoiding asteroids (SphereGeometry) that a ...

Using Vue.js to pass a variable from a parent component to a child component

Parent component: ShowComment Child component: EditComment I'm attempting to pass the value stored in this.CommentRecID to the child component. In the template of ShowComment, I have included: <EditComment CommentRecID="this.CommentRecID" v-if= ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Toggle the flag status of a checkbox based on the response provided in dialogues (Angular)

Query: I am facing an issue with my checkbox system where a dialog pops up when trying to unflag a form by unchecking the box. The dialog asks for confirmation before removing the form. How can I ensure that the checkbox remains checked until the user clic ...

Creating a form in PHP with the power of JavaScript, AJAX, and jQuery

I have successfully created a registration form using HTML, processed the data with PHP, and utilized javascript, ajax, and jquery. However, I am facing an issue where I want to display a notification stating whether the operation was "inserted/failed" on ...

Transform ternary conditional operators into if-else statements

I encountered an issue while attempting to convert a simple minified jQuery code to an if else statement. The error message "Can't find variable: i" is displayed. Check out the original code below: var c = slider.activeIndex; 0 === c ? (slider.slid ...

Utilize a pair of arrays to assign distinct values in JavaScript

I realize the title of my question may seem odd, but I wasn't sure how else to phrase it. I am dealing with two sets of data a = [1,2,3] And b = ["gf","gdf","gdf"] Currently, my return statement looks like this: return { options: a.map(value ...

Execute a JavaScript function when an element loaded via Ajax in a Spring MVC framework triggers the onChange event

I currently have a dropdown list with two values and I am looking to enable or disable four components based on the user's selection. If the user picks the first value, the components should be enabled, otherwise they should be disabled. On the main ...

Engaging with JSON data inputs

Need help! I'm attempting to fetch JSON data using AJAX and load it into a select control. However, the process seems to get stuck at "Downloading the recipes....". Any insights on what might be causing this issue? (Tried a few fixes but nothing has w ...

What is the best way to iterate through an Object.entry and multiply one value by another key value within a loop?

I am looking to enhance the functionality of my Vue.js composition API web application by calculating the total number of employed workers in different sectors. However, I want to multiply the number of workers by another key:value property instead of ju ...

Are there any resources available for optimizing performance on iOS and Android browsers?

Being a web developer means considering the Android and iOS web browsers, which have their own rendering engines and limitations in power and memory. This can pose many complications. Therefore, I'm curious if there is a detailed guide available for ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Unable to remove element from database using Mongoose $pull

I am facing a challenge when trying to transfer an entry from one array to another within the same collection using $pull and $push. While $push works as expected, I encounter issues with $pull not removing the array element. The code snippet I am current ...

Nested JavaScript function expression

In this JavaScript example, the snippet provided is for educational purposes and does not include validation. After defining the variable 'isBetween' within the buildBoundDetector() function, it raises questions about how passing a number through ...

Display the preloaded element as the first item using Javascript

Is there a way to prioritize the loaded elements using JavaScript? I have an array of elements that I pass to a function and make an AJAX call. While the data is loading, I display a loader (.gif). I want to ensure that the loaded elements are shown first ...

Error: Attempting to use hooks outside the scope of a function component in react-native. Hooks can only be called within the body of a

Oops! An error occurred: Invalid hook call. Hooks can only be called inside the body of a function component. There are several reasons why this might have happened: You could have incompatible versions of React and the renderer (e.g., React DOM) Your cod ...

Creating a design utilizing HTML columns with a set height and the ability to scroll horizontally

For my android project, I have a requirement to display a view (WebView) that dynamically loads content. The content will consist of <div class="content-item"> tags that are added by JavaScript to <div class="content-holder"> after the page has ...