title: Handling null values in MongoDB trigger function
body: <p>I have a MongoDB instance configured in MongoDB Atlas. The instance contains two collections:</p>
  <ul>
  <li>Col_A</li>
  <li>Col_B</li>
  </ul>
  <p>When I update any object in Col_B, I have a MongoDB trigger which then uses the information in the Col_B changeEvent and updates part of what is a very large schema in the Col_A object matching the same ID.</p>
  <pre><code>exports = function(changeEvent) {
    
    //Access the _id of the changed document:
    const docId = changeEvent.documentKey._id;
    const mongodb = context.services.get(&quot;MongoDBInst&quot;);
    
    const collection = mongodb.db(&quot;MongoDB&quot;).collection(&quot;Col_A&quot;);
    collection.updateOne(
      { _id: docId },
      { 
        $set: {
          &quot;Field1.Subfield1.Val1&quot;: changeEvent.fullDocument.value1,
          &quot;Field1.Subfield1.Val2&quot;: changeEvent.fullDocument.value2
        }
      }
    );
    console.log(&quot;Data updated for: &quot; + docId);
  </code></pre>
  <p>This works for most objects that already have Field1 and Subfield1 set, however, some of the objects in my database have Field1 or Subfield one set to <code>null</code> which results in the following error:</p>
  <blockquote>
  <p>uncaught promise rejection: write exception: write errors: [Cannot create field 'Val2' in element {Subfield1: null}]</p>
  </blockquote>
  <p>I looked up the error and tried to implement the below:</p>
  <pre><code>exports = function(changeEvent) {
    
    //Access the _id of the changed document:
    const docId = changeEvent.documentKey._id;
    const mongodb = context.services.get(&quot;MongoDBInst&quot;);
    
    const collection = mongodb.db(&quot;MongoDB&quot;).collection(&quot;Col_A&quot;);
    collection.updateOne(
      { _id: docId },
      { 
        $set: {
          &quot;Field1&quot;: {
            &quot;Subfield1&quot;: {
              &quot;Val1&quot;: changeEvent.fullDocument.value1,
              &quot;Val2&quot;: changeEvent.fullDocument.value2
            }
          }
        }
      }
    );
    console.log(&quot;Data updated for: &quot; + docId);
  </code></pre>
  <p>The problem with this, is that <code>Field1</code> doesn't only contain <code>Subfield1</code>, it contains a number of Subfields and this essentially erases the rest of them.</p>
  <p>Any ideas how to use the original dot notation and perhaps create the object prior to assigning the values? I'm new to MongoDB shell so hoping it's something quite simple that I'm missing.</p>