Peck3277
Peck3277

Reputation: 1423

Validating user input in controller and using mongoose schema validators

I'm new to express and mongoose and I'm trying to understand handling data validation.

I have divided up my code into controller, service and dao (model) layers.

In php I'm used to doing my validation in controller layer. If the validation fails I can pass back the 4xx response.

I was tempted to do this in my express controller however after reading about the mongoose validators I'm now unsure. It seems to be the general pattern that you have validators on your mongoose schema. From what I can tell this only covers updating and creating new records. This schema validation doesn't cover methods like find().

So is it a common pattern to validate user data in the controller as well? If so would I not be validating input 3 times in some cases (client, controller, db)?

Upvotes: 0

Views: 341

Answers (1)

user6465102
user6465102

Reputation:

well mongoose validators can do most of the "dirty work" for you by validating the data there and throwing an error in you're express(let's say you are using express) route.

But in general, if you have a schema that can be validated right on the spot, why not use it. In your codebase you would have that one spot right in the Schema that would handle the work, instead of having it buried somewhere in your controller.

I hope this kinda helped :)

Upvotes: 0

Related Questions