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

152
Visualizações
Which approach is more elegant in express.js api routers?

I was doing some practice with express and mongoDB, when I was defining API routes I realized that people on the internet does the first method. But I think second is easier to read especially with bigger data. I wonder if there is a difference or a security issue between them. Thanks in advance.

    // first approach
    router.route("/add").post((req, res) => {
      const email = req.body.email;
      const password = req.body.password;
      const displayName = req.body.displayName;
      const newUser = new User({ email, password, displayName });
      newUser
        .save()
        .then(() => res.json("OK"))
        .catch((err) => {
          res.status(400).json(err);
        });
    });
    
    // second approach
    router.route("/add").post((req, res) => {
      const newUser = new User({ ...req.body });
      newUser
        .save()
        .then(() => res.json("OK"))
        .catch((err) => {
          res.status(400).json(err);
        });
    });
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

when you use mongoose, based on mongoose documentation, By default, documents (req.body) are automatically validated (based on the schema) before they are saved to the database.

This is to prevent saving an invalid document, so there is not a security issue in second approach and It's easier to read, so can use second approach

over 4 years ago · Santiago Trujillo Relatório

0

From the perspective of security, they are the same.

In my opinion, the first approach is better, some practical reasons:

  • easier for other developers to see the data you are saving
  • you may want to do something with the data before saving it
  • helps to maintain the consistency of the code (same structure as where the variables are needed)

You can simplify the declarations using the ES6 destructuring assignment syntax.

From:

const email = req.body.email;
const password = req.body.password;
const displayName = req.body.displayName;

To:

const { email, password, displayName } = req.body;

Also, check the Clean Code JavaScript it may help you decide.

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