Thursday, 18 May 2017

ORM - Object relational mapping with Javascript

I'm working on a NodeJS API project and I'm using CouchDb (Object document storage, similar to MongoDb).

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.

e.g.

var user = new User({name: 'jim'});
user.getName(); // 'jim'

We can then imagine that after we've created a new instance, we save it to the database:

e.g.

await userRepository.add(user); // await = asynchronous flow of ES7

My question is about relational context between entities, imagine that our users has a oneToMany relation with projects .

// 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);

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:

user.getProjects(); // [{ project_1_data }, { ... }];

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:

var projects = user.getProjects(); // [1, 2] list of IDs
await projectRepositories.get(projects[0]); // {...} data of the project

Am i wrong?

How would you represent the relation between multiple entities?

Should objects be in memory during the request runtime or should I just handle relation using IDs even in the domain models.

Please tell me if it's not clear enough. Best regards.



via Simon Bruneaud

No comments:

Post a Comment