Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda