title: MongoDB update nested array foreach
body: <p>I have collection of Users, and each user has an array Ancestors, previous developer did wrong DB architecture, and now each of ancestors is <em>string</em> but must be an <em>ObjectId</em>. It still contain objectId(in fact HEX of object Id, like <code>558470744a73274db0f0d65d</code>). How can I convert each of ancestors to ObjectId? I wrote this:</p>
  
  <pre><code>db.getCollection('Users').find({}).forEach(function(item){
    if (item.Ancestors instanceof Array){
        var tmp = new Array()
        item.Ancestors.forEach(function(ancestor){
            if (ancestor instanceof String){
                 tmp.push(ObjectId(ancestor))
               }
            })
            item.Ancestors = tmp
            db.getCollection('Users').save(item) 
    }
  })
  </code></pre>
  
  <p>But looks like it works not properly, and some of ancestors now is ObjectId, and some <code>null</code>. And also ancestors can be null from start. so I put all that <code>if</code>'s</p>