title: ORM - Object relational mapping with Javascript
body: <p>I'm working on a NodeJS API project and I'm using CouchDb (Object document storage, similar to MongoDb).</p>
  
  <p>In javascript you're free about flow control, because the data structure that you handle are just JSON. So you can just pass object from client to server, and from server to database, without using classes, just passing over the JSON data. However it can be nice to have class that handle this data structures and represent entities.</p>
  
  <p>e.g.</p>
  
  <pre><code>var user = new User({name: 'jim'});
  user.getName(); // 'jim'
  </code></pre>
  
  <p>We can then imagine that after we've created a new instance, we save it to the database:</p>
  
  <p>e.g. </p>
  
  <pre><code>await userRepository.add(user); // await = asynchronous flow of ES7
  </code></pre>
  
  <p>My question is about relational context between entities, imagine that our users has a <strong>oneToMany relation</strong> with projects .</p>
  
  <pre><code>// Create new project and save the project 
  var project = new Project({id: 1});
  await projectRepository.add(project);
  
  // Create new user, add a project to the list, save the user
  var user = new User({id: 1});
  user.addProject(project.getId());
  await userRepository.add(user);
  </code></pre>
  
  <p>In this example the relation between entities is handled manually, since the datastore used is a NoSQL database, and we have to reference the relation directly in our code. OOP languages such as JAVA can use ORM and allows you to do the following:</p>
  
  <pre><code>user.getProjects(); // [{ project_1_data }, { ... }];
  </code></pre>
  
  <p>Because the objects are mapped to the database, and because properties of objects can be other objects.
  A similar use case in Javascript looks like the following:</p>
  
  <pre><code>var projects = user.getProjects(); // [1, 2] list of IDs
  await projectRepositories.get(projects[0]); // {...} data of the project
  </code></pre>
  
  <p>Am i wrong?  </p>
  
  <h3>How would you represent the relation between multiple entities?</h3>
  
  <p>Should objects be in memory during the request runtime or should I just handle relation using IDs even in the domain models.</p>
  
  <p>Please tell me if it's not clear enough.
  Best regards.</p>