2

I am creating mean stack application.How to create structured backend source Like : controller,model,route..etc using express js. I need some examples ?

p7adams
  • 622
  • 1
  • 9
  • 24
  • Does this answer your question? [ExpressJS How to structure an application?](https://stackoverflow.com/questions/5778245/expressjs-how-to-structure-an-application) – EternalObserver Sep 19 '21 at 14:11

3 Answers3

6

First off, there's not one way to do things.

In my experience it's better to separate by business functionality than technical category. Why? Because it gives more context having stuff together that belongs together on functional level than technical level. Also, this allows you to have to switch less between major places of your directory structure. This reduces cognitive load, thus improving your performance.

As an example, let's say we're building a blog website. You only need to separate based on functional parts instead of technical. This allows you to only have one directory open, and focus on the task at hand.

Of course you'll share some things between your functional modules, these you put in a common place.

This would be my approach:

src/
  common/
    db.js
    config.js
  profile/
    User.model.js
    Profile.model.js
    register.route.js
    register.tpl.js
    login.route.js
    login.tpl.js
    forgotten.route.js
    forgotten.tpl.js
  post/
    Post.model.js
    create.route.js
    create.tpl.js
    edit.route.js
    edit.tpl.js
Highmastdon
  • 6,960
  • 7
  • 40
  • 68
4

In our project we have structure like this:

server/
   /common
   /config
   /controllers
   /middlewares
   /models
   /routes
   /tests

In common directory, you can keep all common helper functions or constants.
In the config directory as the name claims you can put all the configs.
In controllers, you keep your controllers.
Middlewares directory is where you can keep your custom middlewares that you want to run before the exact controller.
Models is where you keep your schemas.
Routes is where you keep routes/endpoints.
Test is where you keep tests.

p7adams
  • 622
  • 1
  • 9
  • 24
2

Actually, there is no "correct" structure for express. But there are a lot of recommended approaches. And it's up to you. I recommend you read around for structuring NodeJS projects. But for your case, I would recommend something as follows:

public
views
models
routes
    - index.js # This will hold all routes coagulated into one.
utils          # Utility methods expressed as functions so that you can import them individually
app.js         # This will hold all express bootstrapping code.

For reading material, I will recommend the following:

Ultimately it is worth noting that these are only recommendations and the final structure will be what best suites your project, your client and your team.

cross19xx
  • 3,170
  • 1
  • 25
  • 40