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);
});
});
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
From the perspective of security, they are the same.
In my opinion, the first approach is better, some practical reasons:
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.