How to avoid fat models in a node.js + mongoose app? How to avoid fat models in a node.js + mongoose app? mongoose mongoose

How to avoid fat models in a node.js + mongoose app?


This does indeed smell a little bit.I would use the approach of considering your web app merely as a view of your application.

The best way to ensure this is to never use your mongoose models from your webapp. You could have your webapp living in a process and your model specific logic in another process. The job of that second process would be to take care of your business logic and persistence layer (mongoDB), making it the M in MVC.

Accessing external APIs would take place in that Model layer, we your can separate it from your persistence implementation.

There's a way of communicating between node processes that I like, it's dnode. Once set up, it looks like you are communicating with objects and callbacks within your own process. I would make the webapp and the business app communicating through this in order to get data. The webapp needn't manipulate the actual data and instead sends message to the Model layer (as described by the MVC pattern).

This ensures complete separation between controller/view (webapp) and model+persistence.

One side effect of this organization is that you can easily write other clients of your application, for example a CLI client or a RESTful API.


Are you trying to get id and somedata from url (post/:id/:somedata) ? to construct schema ?

Ideally one should use :

app.post('/reg', function(request, response){console.log(request.body.name);console.log(request.body.email);...}

which is when form is submitted on the 'reg' HTML form page, where you can set all the variables(name,email) in object. In app.post you can get the schema definition from the request itself without having to scan through the url to get variables.

If you still want to know how to get the variables from the url then do this in app.get:

vars=request.url.split('/');//vars contains all the variables you have to use.//use vars to create schema

After you get/create the schema directly pass it to the function / or iterate through the object elements calling that function.