Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda