How can I ensure that I only include a field in a JavaScript object if the value is not null?

In my current setup, I am utilizing mongoose to write data to a MongoDB collection while ensuring there are no null fields. Default values have been set in the document for this purpose. During an update function call, certain fields may be null but I do not want these null fields to trigger any modifications.

For instance:

const Business = require("./businessModel") //Referring to the model
const {id, email, name, contactNumber} = args
const business = await Business.findByIdAndUpdate(
  { id},
  {
   name: ((name != null) ? name : (skip this field))... //HERE
  });

At the marked section, if the 'name' field is not null and contains a value, then update it with the new input value. Otherwise, leave it unchanged and skip this field modification. I do have an alternative method where I fetch the document first and then replace it with the default value from the schema, but I consider this approach suboptimal due to the additional document call it requires.

Answer №1

Your args variable seems to be an object containing relevant fields.

Rather than destructuring all individual properties, you can specifically extract the id and keep the ...rest. Then, you can filter this rest object for null properties.

// example
const args = { id: 1, name: null, email: 'email@domain', contactNumber: 4 };

//const Business = require("./businessModel") //This references the model

const { id, ...rest } = args;
const update = Object.fromEntries(Object.entries(rest).filter(([, v]) => v != null));
console.log(update);

//const business = await Business.findByIdAndUpdate({id}, update);

Explore more options for filtering object properties here: Remove blank attributes from an Object in Javascript

Note: In JavaScript, it's lowercase null, not uppercase NULL. Refer to: why using NULL with logical operator throws error in JS

Answer №2

You may want to consider utilizing update-validators for this scenario. In the specific case mentioned, make sure to validate if the value in the name field is equal to null, and respond to any errors accordingly.

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

Checking the dimensions and information of a JSON collection - a step-by-step guide

Recently, I've encountered a JSON String that was returned with an array inside in my Java SpringBoot application. {... "downlineLevels": ["01","02","03","04","05","06","07"] } Unfortunately, only the following JUnit tests have passed. 1) .andExpec ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

The React data editor Dialog closes when the drop-down is clicked without triggering any onChange events

Utilizing the react-datasheet component, I have implemented a table to display a matrix/grid of data. To enhance user experience, I customized the dataEditor to launch a custom dialog where users can only choose from preselected values in a material-ui dro ...

The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop. Here is the button found on the post: <a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a> And here is the spec ...

Upgrading from synchronous $.ajax() to AngularJS $http or vanilla JavaScript (XHR) for asynchronous calls

Presented below is a function that I am currently working with: function getDataAvailablity() { var isDataAvailable; $.ajax({ url: 'http://someurl/data.json', async: false, dataType: json }).success(function() ...

Height Miscalculation: Chrome and FF encounter window dimension

There is a large application with numerous pages. When I use the console to execute console.log($(window).height()) on any page within the application, it returns the expected result: the height of the window, not the document. For instance: $(window).he ...

Using libcurl for making JSON requests in C language

I am creating a PUT request in C using libcurl with a JSON request body. This is how I am implementing it: sprintf(jsonObj, "\"name\" : \"%s\", \"age\" : \"%s\"", name, age); struct curl_slist *headers = N ...

Implementing a rate limit on the login API that is specific to individual IP addresses rather than being

I have successfully implemented the [email protected] module, but I am facing an issue where it is blocking the API globally instead of for a specific API that is receiving hits. This is my current code: const limiter = new RateLimit({ windo ...

What are the steps to troubleshoot and fix the Internal Server Error on Next.Js?

I recently set up a new Next.js app using the command npx create-next-app. After that, I added Sass to my project with yarn add sass and proceeded to run it with yarn dev. To my surprise, I encountered multiple errors in both my terminal and on localhost. ...

What is the process for configuring socket.io to solely listen on a single designated route?

Is there a way to make socket.io listen only on my /home route, instead of every route? I tried changing the configuration but it only displayed a JSON file on the home path. const server = require('http').Server(app); const io = require('s ...

Seeking a sleeker approach to composing various components with shared functions

Currently, I have a scenario where I have identical components that display data but also need to handle state manipulation and saving. There are 5 other similar components with slight differences in their functions. I am looking for a more efficient way t ...

Click on the checkboxes to the left labeled "Mark"

https://i.stack.imgur.com/2u1dI.png In designing a permission management form for user access, the concept I have in mind is as follows: When "Manage" is selected, the options for view/edit/lend should also be automatically selected and disabled. If any ...

Order of Execution

I am facing an issue with the order of execution while trying to retrieve values from my WebApi for input validation. It appears that the asynchronous nature of the get operation is causing this discrepancy in execution order. I believe the asynchronous b ...

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

What steps need to be taken to set up Node.js to accommodate requests from external sources beyond just localhost?

After creating an application using NextJs, I successfully built it and ran it on a node server by executing 'npm run start' in Powershell. Everything works perfectly when accessing it locally through port 80. However, my Windows Server 2019 does ...

Retrieving a list of numbers separated by commas from an array

Currently, I'm retrieving data from a MYSQL database by executing the following SQL command: SELECT GROUP_CONCAT(MemberMemberId SEPARATOR ',') AS MemberMemberId FROM member_events WHERE event_date = "2000-01-01" AND Eve ...

How to easily transfer a JSON file to a server using Vue and Node.js

As a newcomer to the world of Node.js and Vue development, my goal is to establish a seamless process for users to create and upload a JSON file to the server when they save data in a form. This process should occur effortlessly in the background, allowing ...