title: How to write a mongoose update to update a whole document, various subdocuments included
body: <p>I'm trying to write a way to update a whole MongoDB document including subdocuments using Mongoose and a supplied update object. I want to supply an object from my client in the shape of the schema and then iterate over it to update each property in the document including those in nested subdocuments in arrays.</p>
  <p>So if my schema looked like this:</p>
  <pre><code>const Person = new Schema({
    name: String,
    age: Number,
    addresses: [
      {
        label: String,
        fullAddress: String,
      },
    ],
    bodyMeasurements: {
      height: Number,
      weight: Number,
      clothingSizes: {
        jacket: Number,
        pants: Number
      },
    },
  })
  </code></pre>
  <p>I would want to supply an object to update an existing document that looked something like this:</p>
  <pre><code>{
    &quot;_id&quot;: &quot;217a7f84685f49642635dff0&quot;,
    &quot;name&quot;: &quot;Dan&quot;,
    &quot;addresses&quot;: [
      {
        &quot;_id&quot;: &quot;5f49647f84f02635df217a68&quot;,
        &quot;label&quot;: &quot;Home 2&quot;
      },
      {
        &quot;label&quot;: &quot;Work&quot;,
        &quot;fullAddress&quot;: &quot;6 Elm Street&quot;
      }
    ],
    &quot;bodyMeasurements&quot;: {
      &quot;_id&quot;: &quot;2635df217a685f49647f84f0&quot;,
      &quot;weight&quot;: 90,
      &quot;clothingSizes&quot;: {
        &quot;_id&quot;: &quot;217a685f4962635df49647f84f0&quot;,
        &quot;pants&quot;: 32
      }
    }
  }
  </code></pre>
  <p>The code would need to iterate through all the keys and values of the object entries, and where it found a Mongo ID it would know to update that specific item (like the <code>&quot;Home 2&quot;</code> address label), and where it didn't it would know to add it (like the second <code>&quot;Work&quot;</code> address here), or replace it if it was a property on the top level. (like the <code>&quot;name&quot;</code> property with <code>&quot;Dan&quot;</code>)</p>
  <p>For a one dimensional Schema without taking into account _id's this would work:</p>
  <pre><code>for (const [key, value] of Object.entries(req.body)) {
      person[key] = value;
  }
  </code></pre>
  <p>But not for any nested subdocuments or documents in arrays. I don't want to have to specify the name of the subdocuments for each case. I am trying to find a way to update any Schema's documents and subdocuments generically.</p>
  <p>I imagine there might be some recursion and the Mongoose <code>.set()</code> method needed to handle deeply nested documents.</p>