title: Storing objects with functions and other objects in mongoDB
body: <p>Hi I'm having trouble deciding on the correct way to store my objects in the monogoDB database, from node.js. </p>
  
  <p>A Strip down example of my classes are shown below, in reality it is much more complex:</p>
  
  <pre><code>function Object1{
      var variables;
      var object2:
      var object3:
  
      functions
      ...
  }
  
  function Object2{
      var variables;
      var object4;
      var object5;
      ...
      functions
      ...
  }
  
  ...
  etc
  </code></pre>
  
  <p>A typical function call in Object1 would result in several calls to other objects, and objects belonging to them objects.</p>
  
  <p>If I store object1 in mongoDB, I cannot store the functions. From my research I have two options:</p>
  
  <ol>
  <li><p>Change objects prototype when the object is loaded, as per <a href="https://stackoverflow.com/questions/5777641/storing-and-retrieving-javascript-objects-in-from-mongodb">this answer</a></p>
  
  <p><strong>Question</strong>: I would then be required, to change the prototypes for every subsequent object, but considering the large amount of subsequent objects, this does not seem like the right thing to do, is there an easy way to do this? </p></li>
  <li><p>Use mongoose schemas to define the objects allowing me to use virtuals to store the functions as in <a href="http://mongoosejs.com/docs/2.7.x/docs/virtuals.html" rel="nofollow noreferrer">this example</a>.</p>
  
  <p>Which would result in the following:</p>
  
  <pre><code>var objectSchema = new Schema({
      variables: Type
      object2: Schema.ObjectId
  });
  
  virtual functions
  ...
  </code></pre>
  
  <p><strong>Question:</strong> In this case, each time I wanted to access variables, or call virtual functions in other objects whose ObjectId is in the schema, I would have to call find() on the database. This would potentially result in a large amount of database calls compared to having one database call that loads the object and passing the information round to the subsequent functions, which makes this option also seem invalid?</p></li>
  </ol>
  
  <p><strong>Question:</strong> Is there a better way than these two methods?</p>