title: Mongoose update through $set a value if NOT undefined (NodeJS)
body: <p>what's the proper way to check for undefined values? What I want to do is to have a PUT method that will update those fields that are not empty. For example, if I send <code>req.body.name = 'John'</code> and no <code>req.body.job</code> I want my request to only change the name.</p>
  
  <p>Some code:</p>
  
  <pre><code>router.put('/:id', (req, res) =&gt; {
      const query = {_id: req.params.id};
      const update = {
          $set: {
              name: req.body.name,
              job: req.body.job
          }
      };
  
      User.findOneAndUpdate(query, update,
          (err, userUpdated) =&gt; {
              if (err) {
                  console.log('Error while updating');
                  console.log(err);
              } else {
                  res.send(userUpdated);
              }
          });
  });
  </code></pre>
  
  <p>This will of course throw an error:</p>
  
  <pre><code>CastError: Cast to number failed for value "undefined" at path "job"
  </code></pre>
  
  <p>Now I can manually check if <code>req.body.job</code> is empty and if it is set it's value to the value the user had previously, but that seems like a hack, not elegant and a lot of writing for each route.</p>
  
  <p>I have checked the <a href="https://docs.mongodb.com/manual/reference/operator/update-field/" rel="nofollow">docs</a> but none of the options provided there seem to do the job. I also came across something like <a href="https://github.com/ctavan/express-validator" rel="nofollow">express validator</a> but this will probably just do a <code>return</code> if the value is empty. Another options would be to simply send the value from the front-end part.</p>
  
  <p>I'm new to backend development and I'm not sure if I'm doing stuff the "right way". So please, any comment on how it should be done would be nice (also if my code looks odd, feel free to guide me :)), thanks!</p>