× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Node / Express / MongoDB nested objects not updating

Dale Lotts
Mar 19, 2015
<p>A very common pattern in Node / Express applications is to have the incoming JSON update the existing object by using the lodash .extend method.</p> <p>The original code might look like this:</p> <pre>user = _.<span style="color:#ffc66d">extend</span>(user<span style="color:#cc7832">, </span>req.<span style="color:#9876aa">body</span>)<span style="color:#cc7832">;</span></pre> <p>This works fine until you have nested objects, then the nested objects do not get updated.  One way to fix this is to explicitly set the nested object properties. I'm not a fan of this approach because is does not handle the general case (i.e. nested objects with nested objects) </p> <p>My preferred way to deal with this is to convert the object to JSON, merge with the request body, and then extend the existing object with the newly created merged object. </p> <p>The updated code that will correctly update nested objects is the following</p> <pre>var<strong> </strong>data = _.<span style="color:#9876aa">merge</span>(user.<span style="color:#ffc66d">toJSON</span>()<span style="color:#cc7832">, </span>req.<span style="color:#9876aa">body</span>)<span style="color:#cc7832">; </span>var updatedUser = _.<span style="color:#ffc66d">extend</span>(user<span style="color:#cc7832">, </span>data)<span style="color:#cc7832">;</span></pre> <p>Give it a try and let me know what you think.</p>
comments powered by Disqus