Retrieve an element from an array using the POST method

I am currently working on implementing a POST method using mongo/mongoose:

Department
    .create({
        name: req.body.name,
        link: req.body.link,
        state: req.body.state,
        requirements: req.body.requirements,
        salary: req.body.salary,
        description: req.body.description
    })

The requirements field is structured as an object with multiple items:

requirements: {
    age: 21,
    citizenship: "yes",
    degree: "4-year"
}

Prior to creating the data, I need to ensure that all required fields are provided:

router.post('/create', (req, res) => {
const requiredFields = ["name", "link", "state", "age", "citizenship", "degree" "salary", "description"];
for(let i=0; i < requiredFields.length; i++){
    const field = requiredFields[i];
    if(!(field in req.body)){
        const message = `Missing \`${field}\` field in request body`;
        console.error(message);
        return res.status(400).send(message);
    };
};

Since age, citizenship, and degree are nested within the requirements object, directly including them in the requiredFields list causes an error like

Missing age field in request body
. Any suggestions on how to properly validate their presence in req.body?

Answer №1

  1. If you want to access the nested object, you can save your required field as "requirement.age" instead of just "age" and then utilize the get function in lodash library. This way, your condition would be:

`

if (typeof(_.get(req.body, "requirement.age") === 'undefined')) {
  //Missing field    
}

`

  1. Another approach is to flatten the req.body structure by merging it with req.body.requirement:

Object.assign(req.body, req.body.requirement)

// This will transform req.body into:

{
  name: 'x',
  link: 'y',
  requirement: {
    age: 1
    ..
  },
  age: 1
  ..
}

Alternatively, you can assign it to another variable for further use.

let reqBodyReplica = Object.assign({}, req.body, req.body,requirement)

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

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

Unable to trigger a click on the submit button using JavaScript

I'm encountering difficulties in triggering a click using JavaScript on a Mailchimp pop-up subscribe form and I require your assistance. <!-- Title & Description - Holds HTML from CK editor --> <div class="content__titleDescripti ...

Looking to automatically scroll to the bottom by clicking on text using javascript/jquery?

I am currently working on a website project where I have a specific requirement. I need the webpage to scroll towards the bottom when a particular text is clicked, using JavaScript/jQuery. <p class="ml-2 mb-2 d-flex view_profile_options"><a hre ...

Using NodeJs and MongoDB to retrieve a specific document based on its parameter value

Here is how my MongoDB structure looks like: https://i.sstatic.net/TkgOg.png I am trying to create a query that will retrieve all keys and values of a single document in the database. The document needs to have a key "content-transition" with a value of ...

Exploring the world of JSON objects within React

Let me explain the scenario: I have a basic nodejs backend (using express and mongoose) that responds to GET requests with JSON data (formatted as an Object of objects). After receiving the response, I want to render a component for each element within t ...

Verify if the user is currently inputting text within a specific range of characters within

I am dealing with a specific issue involving a textarea. By default, this textarea contains a string of any type, but a user is only able to type inside opening and closing brackets. For example, "Leave[]" allows typing within the brackets but not outsid ...

Utilizing a dictionary within an Angular controller

Currently, I am working on a complex process that involves Angular and MVC controllers interacting with a REST API to retrieve configuration items. The challenge lies in transforming this data into a usable format within the Angular controller for various ...

Tips for preventing multiple requests in your JavaScript search autocomplete feature

I'm currently using the Turbolinks.visit action with the help of $(document).on("input");... HTML <form id="mainSearch" method="get" autocomplete="off"> <input type="search" name="s" placeholder="Search" /> </form> Javascript ...

Newbie in PHP: Techniques for transferring PHP variables between different sections of PHP code

In my project, I have a file named index.php which is responsible for uploading files to the server and setting PHP variables such as $target_folder_and_file_name. This index.php file also includes the following line (originally it was in an index.html fi ...

Regularly send requests to an Express server using the $.get function

Operating an Express server with a time generator to send generated time data to the client page gtm.hbs. How can I implement regular polling of the server from the client using Ajax? Displayed below is the server-side code located in \routes\ge ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Utilizing AngularJS: Transforming JSONP information into HTML

I'm relatively new to utilizing $http and fetching data from various websites. My main query is, how can I convert JSONP into HTML? Specifically, when using $http to request the Atari Wikipedia page, the content is displayed with and HTML elements. ...

Guide on populating a table with user input using jQuery and ajax

For the past few days, I've been attempting to populate a table using jQuery and ajax based on search results, but unfortunately, it's not working out for me. Below is the HTML code snippet: <form class="form"> <div class="form-gro ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Choose the tag and class then retrieve the custom attribute

I'm currently attempting to retrieve a specialized attribute utilizing jquery and subsequently choose it, nevertheless I am encountering some difficulties with the process Below is the jquery code I have implemented to access the value var stockId = ...

Guide on fetching data from a different php file using jQuery's .load() method?

I am trying to use a basic .load() function from jQuery to load a div element with an id from another file in the same directory when changing the selected option in a selector. However, I am having trouble getting it to work. Nothing happens when I change ...

Ways to efficiently verify if a URL is valid by checking if it loads a page with content

INQUIRY: How can I verify if a URL is valid and loads a webpage successfully? Currently, my code only checks the status code, which means that a URL like will be considered valid even though it does not load any content. Is there a way to ensure that t ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Having trouble with your browser freezing up after an AJAX request finishes?

Going through a tough time trying to figure this out for the past two days, but still struggling without any clue. Here's what I've been up to: Firstly, I upload a file using AJAX and instantly start processing it on the backend. $.ajax({ t ...

Importing ES module into Next.js leads to ERR_REQUIRE_ESM

Encountered this issue while attempting to integrate ky into a Next.js project: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js It seems that the cause of this problem is Webpack (or Babel) converting all import ...