Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

464
Visualizações
How to follow MVC architecture in web app Using Node, Express, Postgresql

I'm unsure of how to apply the MVC architecture to my node web app, in specific separating the model from the controller.

The current structure has the views separated properly (all my .ejs files) and then I guess that my app.js is like the controller as it contains all the routes to respond to http requests. The routes are then handled in a queries.js file which is where I query my database using node-postgres (most of the views rendered are either displaying information from the database or displaying forms so the user can insert data to the database). Should I be doing this differently, or more specifically should I try to create a model that contains raw data from the database and have the route handlers manipulate this data instead of directly querying the database (not sure how I would handle inserting into the database then...)? I'm just concerned that the current way I have structured my web app will make it difficult to manage as it grows and difficult for other to understand and add on to.

Here is an example of how the web app is currently structured: Say a user clicks a button to display all the active orders, my app.js file would look something like this

const db = require('./queries')

app.get('/activeorders', db.getActiveOrders)

My queries.js file would then handle this route like so:

const Pool = require('pg').Pool
const pool = new Pool({
  user: process.env.USER,
  host: process.env.HOST,
  database: process.env.DB,
  password: process.env.PASSWORD,
  port: process.env.PORT,
})

const getActiveOrders = (request, response) => {
    const queryOrders = 'SELECT * FROM orders WHERE complete=0 ORDER BY date_rec DESC;';
    pool.query(queryOrders, (error, results) => {
        if(error) {
            throw error
        }
        var ordersObj = results.rows;
        response.render('pages/activeorders', {
            ordersObj: ordersObj
        })
    })
}

module.exports = {
    getActiveOrders,
}

As can be seen in the handler the database is queried and stores the results in an object that is then passed to the activeorders.ejs file when rendered.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

In MVC pattern we split each part of the application because this approach to software development for complex needs by connecting the implementation to an evolving model

I suggest you visit sample-mvc-express-postgres to understand structure code

If you are interested in design pattern, visit https://dev.to/salah856/implementing-domain-driven-design-part-i-5a72, This link explains how to use DDD in your application and show how to design each layer of the application

over 4 years ago · Santiago Trujillo Relatório

0

Maybe using a middleware allowing you to make an API from a Postgresql database.

Any change made on the databases will be propagated and available to you API. It will also let a lot of modularity to possible filters/ select ...

And for complex queries DBA will be able to develop stored procs available to everyone by API. That is the Model layer. Only SQL exposed through a middleware.

Controller will be how you made you API calls and data transformations if needed to refresh data based in you View

Abstracting the model layer with a middleware definitely a huge economy on time.

For postgres majors options : postgres & pgrest

over 4 years ago · Santiago Trujillo Relatório

0

Set app.js as root file and create a controller and a model folder. Define all models in model folder, while in controller first import model files handlers and create all APIs or queries function. Then in the root app.js file import controller functions handler and run it.

this image contain folder structure

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda