Abstract: should I use express-validator if I can validate data using mongoose schema?
I’m a front end developer, and I usually do some validation on the form before submitting. Now, I’ve started studying express.
One of the first things I did was receive a form and validate it using a library called express-validator, then the database operations were done. very simple, no big deal. However, after doing a project by myself I realized that mongoose itself could handle the errors, not only that, but it was quite easy to return these errors on the front, especially in the case of an api.
So that is my doubt, why validate this data so many times? I know that database schemas is not only to do that, but doing theses things once in front and twice in backend cause too many
repetition and may be a little hard to maintain.
Here goes a few lines of code only to illustrate the case. Don’t judge me, I’m still learning.
import mongoose from "mongoose";
const TaskSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
maxlength: 20,
},
description: {
type: String,
required: false,
},
completed: {
type: Boolean,
default: false,
},
date: {
type: Date,
default: Date.now,
},
});
export default mongoose.model("Task", TaskSchema);
import taskModel from "../models/tasksModel";
export function createTask(req: express.Request, res: express.Response) {
taskModel
.create(req.body)
.then((task) => res.status(201).send(task))
.catch((err) => res.status(400).send(err));
}