Express.js and Mongoose model relationships - in model or router?


Building a REST API with Express.js and Mongoose on node - I have stumbled upon a code design issue - where should I handle relationships - in models or routers?

First, I am pretty new to the MVC and such, and even though express.js is not a full MVC, I would like to follow best design practices.

The issue is rather easy - the app has users, each user can have multiple documents (projects, orders, etc). Obviously I have to at least store the user ID for every document that is created. The question is - where should I do that?

I can get the user ID from the session in each router and attach it to a document, or I can just set the current user ID to a global variable, for example app.currentUserID and use that in my model to attach the ID to the document.

There are actually more interesting cases, where a user can have multiple organizations, and I have to set the organization ID for each document that the user creates when operating with a specific organization.

So the question is: should I handle this kind of logic in my router (express does not have 'controllers' as such) or model?

12/7/2012 10:20:57 AM

Accepted Answer

Do it in the model. Even if you're not creating an enforced relation, storing the actual ID of a related object still changes the model, so there's no reason to leave the logic in the router.

MongoDB (and Mongoose) doesn't have referential integrity like relational databases do. This means that the database will not give you an error if you insert a relation to an object which doesn't exist. It lets the application code handle those relations.

Mongoose is an attempt to bring structure to an otherwise pretty liberal nosql DB. As such, it offers an ability to create such relations with the ObjectId schema type.

Read the following SO answer for more info:

5/23/2017 12:33:49 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow