Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!