title: Node.js - Mongoose - Update nested array with all values in req.body
body: <p>
  I have an object that looks like this.</p>
  
  <pre><code>{
    _id: '577fe7a842c9b447',
    name: 'Jacob\'s Bronze Badges',
    competitors: [
      {
        _id: '577fe7a842c9bd6d',
        name: 'Peter\'s Silver Badges',
        sites: [
          {
            _id: '577fe7a842c9bd6d',
            name: 'Facebook',
            url: 'fb.com/peter'
          },
          {
            _id: '577fe7a842c9bd6d'
            name: 'Google',
            url: 'google.com/peter'
          }
        ]
      },
      {
        _id: '599fe7a842c9bd6d',
        name: 'Paul\'s Gold Badges',
        sites: [
          {
            '_id': '577fe7a842c9bd6d',
            name: 'Facebook',
            url: 'fb.com/paul'
          },
          {
            _id: '577fe7a842c9bd6d',
            name: 'Google',
            url: 'google.com/paul'
          }
        ]
      }
    ]
  }
  </code></pre>
  
  <p>My goal is to reference the <code>competitors</code> array and update items inside with all of the values from <code>req.body</code>. I based this code off of <a href="https://stackoverflow.com/questions/23577123/update-nested-array-with-mongoose-mongodb">this</a> answer, as well as <a href="https://stackoverflow.com/questions/15691224/mongoose-update-values-in-array-of-objects">this other one</a>.</p>
  
  <pre><code>Location.update(
    { 'competitors._id': req.params.competitorId, },
    { $set: { 'competitors.$': req.body, }, },
    (err, result) =&gt; {
      if (err) {
        res.status(500)
        .json({ error: 'Unable to update competitor.', });
      } else {
        res.status(200)
        .json(result);
      }
    }
  );
  </code></pre>
  
  <p>I send my <code>HTTP PUT</code> to <code>localhost:3000/competitors/577fe7a842c9bd6d</code> to update Peter's Silver Badges. The request body is:</p>
  
  <pre><code>{
    "name": "McDonald's"
  }
  </code></pre>
  
  <p>The problem is that when I use <code>$set</code> to set the competitor with <code>_id: req.params.competitorId</code>, I don't know what is in <code>req.body</code>. I want to use the entire <code>req.body</code> to update the object in the array, but when I do, that object is overwritten, so instead of getting a new name, Peter's Silver Badges becomes:</p>
  
  <pre><code>{
    name: 'McDonald\'s',
    sites: []
  }
  </code></pre>
  
  <p>How can I update an object within an array when I know the object's <code>_id</code> with all of the fields from <code>req.body</code> without removing fields that I want to keep?</p>
  
  <p>I believe that the <code>sites</code> array is empty because the object was reinitialized. In my schema I have <code>sites: [sitesSchema]</code> to initialize it. So I am assuming that the whole <code>competitors[_id]</code> object is getting overwritten with the new name and then the <code>sites: [sitesSchema]</code> from myschema.</p>