Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How do I only add the field in an object if the value isn't null? Javascript

I am currently using mongoose to write data to a document in a MongoDB collection but I accept no null fields, I already have set default values in the document. I call an update function that has some fields as null, those fields that are null already, I do not want them to make a modification.

Example:

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

Where I commented here, if the name is not null, which means a value exists for it then have the predefined schema value name now set to the new name input, otherwise don't change anything and just skip the field. I do already have an alternative where I call the document first then replace it with the default value for the document but that requires a document call which I do not believe to be an optimal solution.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try using update-validators. So in your case, check if value in name field === null, and handle the error response as required.

about 4 years ago · Juan Pablo Isaza Report

0

It looks like your args variable is an object with the relevant fields.

Instead of destructuring all the individual properties, you can extract just the id and leave the ...rest. You can then filter this rest object for null properties.

// mock
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);

More options for object property filtering here: Remove blank attributes from an Object in Javascript

Note: NULL doesn't exist, the null object in javascript is lowercase null. see: why using NULL with logical operator throws error in JS

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!