title: Mongo - Replace references with embedded documents
body: <p>I have a Collection with a nested attribute that is an array of ObjectId References. These refer to documents in another Collection.</p>
  <p>I'd like to replace these references with the documents themselves, i.e. embed those documents where the references are now. I've tried with and without the .snapshot() option. This may be caused because I'm updating a document while in a loop on that doc, and .snapshot() isn't available at that level.</p>
  <p>My mongo-fu is low and I'm stuck on a call stack error. How can I do this?</p>
  <p>Example code:</p>
  
  <pre class="lang-js prettyprint-override"><code>db.CollWithReferences.find({}).snapshot().forEach( function(document) {
      var doc_id = document._id;
      document.GroupsOfStuff.forEach( function(Group) {    
          var docsToEmbed= db.CollOfThingsToEmbed.find({ _id: { $in: Group.ArrayOfReferenceObjectIds }});
  
          db.CollWithReferences.update({&quot;_id&quot;: ObjectId(doc_id) },
              {$set: {&quot;Group.ArrayOfReferenceObjectIds &quot;:docsToEmbed}} )
      });
  });
  </code></pre>
  <p>Gives this error:</p>
  <pre class="lang-js prettyprint-override"><code>{
      &quot;message&quot; : &quot;Maximum call stack size exceeded&quot;,
      &quot;stack&quot; : &quot;RangeError: Maximum call stack size exceeded&quot; +
      ....}
  </code></pre>