Organising folder structure and database queries with nodejs, express, mongoose using an MVC pattern Organising folder structure and database queries with nodejs, express, mongoose using an MVC pattern mongoose mongoose

Organising folder structure and database queries with nodejs, express, mongoose using an MVC pattern


1. Should the config/passport.js file contain mongoose db connections?You can put your mongoose db connections in a separate file called db.js, then import or require that file in passport.js. So your config folder could look like this

/config /db.js /passport.js

2. Is the mongoose user schema code in the correct place?Yes, but you should capitalize the first letter of your model files to follow convention User.js.

3. Is this right or wrong to place the db connection there in my controllers/routes.js file? If it is wrong where should I place it and how should I call the function which accesses the mongo database?You are not placing your db connection in the routes.js file. Your connection to your db should go in your config folder config/db.js. You would then export the file module.exports = db; and require it var db = require('/config/db.js'); in your controllers/routes.js file. Now you will have access to your db connection. You could now run Mongo queries and methods in your controllers files, which is where your app's logic should go.

Your Model only speaks to your Controller, not the View. Similarly, your View only speaks to your Controller. Keeping your code organized this way will make your life much easier when your app gets more complicated.


I would add another 'services' folder and add some kind of db-accessor service in there.You can still place all your db configs in your config file and let the service take it from there.

Another nice thing you can do is define the passport mongo-strategy in a separate moduleso that it will also be replaceable.


If you want to get up and running more quickly with node, express, and mongo, take a look at sails.js. It's the most popular node.js MVC framework nowadays, and will help you spin up this type of project more easily.