Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda