Reputation: 196
I have a controller that when i insert data into the database it always inserted. Now i wanna check that if the data i create is null is must report an error. Here is my code:
// create new car
export async function createCar (req, res) {
const car = new Car({
car_id: id,
name: req.body.name,
color: req.body.color,
brand: req.body.brand,
});
return car
.save()
.then((newCar) => {
return res.status(201).json({
success: true,
message: 'New car created successfully',
Car: newCar,
});
})
.catch((error) => {
console.log(error);
res.status(500).json({
success: false,
message: 'Server error. Please try again.',
error: error.message,
});
});
}
And i check on postman even i let Name is NULL is still inserted. Furthermore, how can i check that COLOR, BRAND if it's null must also report an error. Please help me.
Upvotes: 1
Views: 599
Reputation: 196
For validate before insert
// Validate request
if (!req.body.name)
{
res.status(400).send
({
message: "Name can not be empty!"
});
return;
} else if (!req.body.color)
{
res.status(400).send
({
message: "Color can not be empty!"
});
return;
} else if (!req.body.brand)
{
res.status(400).send({
message: "Brand can not be empty!"
});
return;
}
Upvotes: 0
Reputation: 1039
Kato, please follow my boilerplate. I created it with the best practices, and it also provides high-end JOI request validation.
A boilerplate for building production-ready RESTful APIs using Node.js, ExpressJs, Mongoose and Joi (Request Validation)
Upvotes: 1