Home > database >  How do I only add the field in an object if the value isn't null? Javascript
How do I only add the field in an object if the value isn't null? Javascript

Time:10-18

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.

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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

  • Related