JavaScript code running Array.every() to validate API query parameters, resulting in a false output

Trying to verify whether an API query parameter can be updated. ['age"]

I am comparing it against an array of properties.

Unfortunately, the result keeps returning as false

I have used console.log() to debug.

  • parameters
  • list of properties
  • Result of checking parameters against properties list



    router.patch('/users/:id', async (req, res) => {

    const updates = Object.keys(req.body);
    const properties = ['name', 'age', 'email', 'password'];

    console.log(updates)
    console.log(properties)

    const validateUpdate = updates.every((item) => {
        properties.includes(item);
    });
    console.log(validateUpdate);
    try {
        if (!validateUpdate) {
            console.log(`Property not eligible for update: ${validateUpdate}`);
            return res.status(400).send('Property not eligible for update');

        }
        const updateUser = await User.findByIdAndUpdate(req.params.id, req.body, {
            useFindAndModify: false,
            new: true,
            runValidators: true
        });
        res.status(200).send("update" + updateUser);
    } catch (error) {
        res.status(400).send(error)
    }

});

https://i.sstatic.net/nbe73.png

Answer №1

You failed to add a return statement in the every callback function, causing it to always return undefined, which results in a falsy value.

To solve this issue, simply add a return statement before the includes statement or remove the curly brackets {}.

const validateUpdate = updates.every((item) => {
    return properties.includes(item);
});

Answer №2

Issue with return statement:

const checkValid = updates.every((value) => {
  myList.contains(value);
});

Solution:

const checkValid = updates.every((value) => myList.contains(value));

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

Automatically updating the checkable prop of an HTML checkbox based on value using Javascript and Jquery

I have created a JavaScript file to handle checkboxes, but I am facing an issue where the checked property of the checkbox is not updating based on the input value. This is because my template engine directly renders boolean values to the input value attri ...

The Route.go function is ineffective when used in form submission

Hey there! I'm new to the world of meteor and javascript, currently working on a fun little app project. My tool of choice is meteor with ionic. Here's a snippet from my simple form: <form> .... <label class="item item- ...

Error Occurs While Getting Request Parameters with Ajax Post and Express.js

When utilizing ajax to send data from a JavaScript frontend to an Express.js backend server, I am having trouble retrieving the posted data in the API method of my express.js. Below is the code where I attempt to parse the request data. Your assistance i ...

Creating a Dynamic Bar in Your Shiny Application: A Step-by-Step Guide

Currently, I am developing a unique crowd funding shiny app to monitor donation amounts. Is there a method available that allows for the creation of a reactive bar in Shiny? Alternatively, is it feasible to achieve this using html, css, and javascript? He ...

Two ng-click events are triggered within a nested ng-click

I am facing an issue with using the ng-click within a nested list under another list that also has a ng-click event. Here is my code snippet: <ul> <li ng-repeat="facet in node.Facets" ng-click="updateNav(facet.Action)" ng-cloak & ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

Concealing tab bars on Ionic 2 secondary pages

In my Ionic Bootstrap configuration, I have the following setup: { mode: 'md', tabsHideOnSubPages: true } However, despite having this setting in place, the tabs still appear on some sub-pages. It seems to be happening randomly. Is there ...

Issue with event handling in react-leaflet polygon component

Curious question, my experience involves dynamically rendering Polygons with the help of react-leaflet. The polygons are displaying as expected. However, whatever configurations I apply to eventHandlers seem to have no effect. const highlightFeature = ( ...

Differences between throwing errors, returning error objects, and using callbacks in Javascript

Currently, I am developing an assembler and simulator for a simplistic assembly language that my computer science students use during their classes. The project is being written in JavaScript with the intention of creating a user-friendly interface in the ...

Creating unique layouts for mobile and desktop using vuejs

Searching for a sleek and intelligent method to offer users varying layouts or components based on mobile or desktop views using Vue. My web application includes many tables, but we all know that tables can be clunky on a mobile device. I'm consideri ...

Using Webpack to create a React app that acts as a proxy to an Express server. The app retrieves and displays JSON responses from the server

I've encountered an issue with my React web app that utilizes Express as the backend. The setup involves proxying request URLs from the React server port (9000) to the Express server (3000). However, when entering a specific path such as /examplepath ...

The error in ReactJS is coming from the render method of the `News` component

While working with React JS, I encountered an error when trying to run a particular code snippet. The error message displayed was: "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

Encountering difficulty rendering information within React and Redux component

I'm having trouble displaying some placeholder data on my component, as nothing is showing up. When I console.log the expected output, I see [object Object]. I suspect there might be an issue with my actions, actionCreators, and reducers. #actions/t ...

Include a selection of images within a popover box

I am currently working on a component that contains various experiences, each with its own popover. My goal is to display an array of images within each popover. Specifically, I have different arrays of images named gastronomiaExperience, deportesExperien ...

Incorporate JSON data to display SVG images

As a beginner in web development, I have been honing my skills with the AngularJS framework due to its user-friendly nature. Currently, I'm working on pulling JSON data from an API using $http.get method. One of the fields contains an image source i ...

Is it necessary to reset the unordered list after adding it to the scrollbox?

I am facing an issue with my <ul> element that has overflow:auto; set. I want to dynamically add new <li> elements using the append(); method, but I can't seem to automatically scroll the box to the bottom after adding a new <li>: H ...

What is the best way to display long text in a browser alert without it being cut off?

Seeking to display a large amount of data in an alert box, but only a portion is currently visible. The following text is all that can be seen: ["19467,1496257152583","19227,1496256651094","19469,1496257033968","17285, ...

Struggling to retrieve POST parameters when using expressJs and AngularJs for POST requests

When attempting a post request with Angular, I am unable to access my post parameters. Below is my Angular code: var request = $http({ method: 'POST', url: '/api/login', data: { ...

Troubleshooting: Express router does not correctly implement Mongoose's findByID method when using URL route

After following a tutorial, I encountered an issue with the code: /* GET one item. */ router.get('/items/:id', (req, res) => { Item.findById(req.param.id, (err, items) => { if (err) res.status(500).send(error) res.status(200).js ...