title: Null Pointer Exception trying to set a field of a nested document with Spring Data MongoDB- Java
body: <p>I'm using Spring Data MongoDB to access the data layer of my Java application.
  This is a document of my collection called <code>people</code>:</p>
  <pre><code>{  
      &quot;_id&quot;: {
         &quot;$oid&quot;: &quot;6214acefbef59f9df6b4482c&quot;
      }
      &quot;firstName&quot;:&quot;Bilbo&quot;,
      &quot;lastName&quot;:&quot;Baggins&quot;,
      &quot;createdDate&quot;: {
          &quot;$date&quot;: &quot;2022-03-17T08:01:59.612Z&quot;
      },
      &quot;modifiedDate&quot;: {
          &quot;$date&quot;: &quot;2022-03-17T00:19:16.563Z&quot;
      },
      &quot;books&quot;: [{
          &quot;title&quot;: &quot;There and Back Again&quot;,
          &quot;publisher&quot;: &quot;Tolkien Gateway&quot;,
          &quot;price&quot;: 25.78
      }]
  }
  </code></pre>
  <p>Obviously, keep in mind that the &quot;books&quot; array is not mandatory, so it may be absent.
  For instance, I could have the following document in the <code>people</code> collection too:</p>
  <pre><code>{  
      &quot;_id&quot;: {
         &quot;$oid&quot;: &quot;623104d138693c0353cfecc6&quot;
      }
      &quot;firstName&quot;:&quot;Frodo&quot;,
      &quot;lastName&quot;:&quot;Baggins&quot;,
      &quot;createdDate&quot;: {
          &quot;$date&quot;: &quot;2025-03-17T08:01:59.612Z&quot;
      },
      &quot;modifiedDate&quot;: {
          &quot;$date&quot;: &quot;2025-03-17T00:19:16.563Z&quot;
      }
  }
  </code></pre>
  <p>Now I would like to show you this snippet code to add a book to the previous document:</p>
  <pre><code>var aNewFrodoBagginsBook = new Book(&quot;The Fellowship of the Ring&quot;, &quot;Tolkien Gateway&quot;, 55D)
  var aPerson = peopleRepository.findById(&quot;623104d138693c0353cfecc6&quot;);
  aPerson.getBooks().add(aNewFrodoBagginsBook);
  peopleRepository.save(aPerson);
  </code></pre>
  <p>The previous code throws a <code>NullPointerException</code> since <code>aPerson.getBooks()</code> is null.</p>
  <p>When I need to save some data of a nested mongodb object with the <code>repository.save</code> method and I'm not sure if a certain field is present or not, should I always pay attention to verify that the object is not null before doing the set?</p>
  <p>I just changed the previous code with the following but I'm not sure this is the right way to go ahead:</p>
  <pre><code>var aNewFrodoBagginsBook = new Book(&quot;The Fellowship of the Ring&quot;, &quot;Tolkien Gateway&quot;, 55D)
  var aPerson = peopleRepository.findById(&quot;623104d138693c0353cfecc6&quot;);
  Optional.ofNullable(aPerson.getBooks()).orElseThrow(MyCustomException::new).add(aNewFrodoBagginsBook)
  peopleRepository.save(aPerson);
  </code></pre>