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

Is it possible to use Koajs without needing to include the --harmony tag?

Following the merge of iojs into Node, I assumed that I could run koajs without the need for the --harmony tag (as it would have support for generators from es6). Inside my server.js file, I have the following code: var koa = require('koa'); va ...

Enhancing Django Datatables by sending additional data from server to template

After successfully implementing the dataTables plugin with django server-side processing, my code looks something like this: In the template: <script type="text/javascript"> $(document).ready(function() { $('#example').dataTable( ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

A div containing a form, with the form being visually integrated within the div

Hi everyone, this is my first post here and I've tried to search extensively before asking this question. I've attempted to use the following examples without success: jquery submit form and then show results in an existing div Form submit ...

I'm having an issue with my progress bar in ReactJS - it seems to move when I scroll the window instead of

My code includes a progress bar that works fine - it shows a movable progress bar when the window is scrolled. However, I want the progress bar to move when scrolling inside my div, not on the entire window. I am currently using jQuery for this functionali ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

Utilizing Multer for temporarily storing a file in memory before parsing and transferring it to the database

As a newcomer to programming, I am attempting to describe my issue concisely. I am utilizing multer to upload an XML file in conjunction with a Node Express server and React with .jsx. My intention is to parse the uploaded file data and post it to a Postgr ...

p5.js experiencing issue: Uncaught TypeError - Unable to access property 'transpose3x3' due to null value

I have a simple website built with Flask where I am running several p5.js sketch animations, and everything is working smoothly. However, when I try to add a new sketch that utilizes WEBGL, I encounter the following error: Uncaught TypeError: Cannot read p ...

The functionality of window.location.href seems to be malfunctioning on mobile devices within an ionic application

Attempting to open a view with a function call from the UI side <ion-option-button class="button-light icon ion-chatbubble" ng-click="openView('username')"></ion-option-button> The controller code for this action is as follows: $sc ...

Ways to require semicolons in a Typescript interface

When declaring a TypeScript interface, both , (comma) and ; (semicolon) are considered valid syntax. For example, the following declarations are all valid: export interface IUser { name: string; email: string; id: number; } export interface IUser { ...

Storing JSON data from a Github Gist in an array using the AJAX method - a step-by-step guide

I'm experimenting with storing JSON data in a variable and then randomly accessing it. (Superhero Alias Generator) The JSON data can be found on GitHub gist below I decided to try using the ajax method for the first time, but it doesn't seem to ...

Comparing the parsing of fetch() JSON response output in Node.js to parsing a JSON variable

Could someone clarify the difference between parsing a Variable JSON object and parsing fetch() response data JSON object stored in a variable? For example: If we have a variable like this: var myJSON = { "items" : [ { "id" : &q ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...

How should I arrange this data in MongoDB?

Currently, I am in the process of designing and developing an application using Python. This application will run nightly, taking a website and a list of keywords and querying the Google API to determine their position for a specific keyword. My intention ...

A step-by-step guide on extracting multiple values from a JSON response using Java

I need to extract multiple values from a JSON response that my code generates. The response looks like this: { "data": [ { "boxnumber": "1", "quantity": 1, "product": "7010501264", "packdate": "2014-10-16 20:59:25.632533" ...

Exploring the possibilities of JavaScript within the IntelliJ REST client

I've delved into the extensive documentation provided by JetBrains on their HTTP Client and how to incorporate requests using files with a .http extension. The challenge I'm facing involves utilizing a function from a separate .js file within on ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

Error: undefined callback function in asynchronous parallel execution

Encountering the error message "callback is not defined" while attempting to utilize async.parallel has left me puzzled. Most examples of async.parallel demonstrate functions being inline, as shown in the async documentation here: https://caolan.github.io/ ...

Attributes of the host element in Angular 1.5 components

I am seeking a way to customize attributes on the host element for Angular 1.5 components. What is the purpose? I would like to assign a class to a component in order to apply specific styles. For example, if the parent component has display: flex set, ...

Which is the better approach for performance: querying on parent selectors or appending selectors to all children?

I currently have 2 mirror sections within my DOM, one for delivery and another for pickup. Both of these sections contain identical content structures. Here's an example: <div class="main-section"> <div class="description-content"> ...