处理数据验证的最好的地方,用mongoose和express [英] Best place to handle data validation with mongoose and express
问题描述
- 模型(mongoose)
- Controller / Route(express)
我读过的一些较旧的帖子是: / p>
但冲突的答案只是增加了混乱。也许它根本不清楚,在这种情况下是一个更好的选择?
当使用mongoose时,我会推大多数我的验证逻辑到mongoose模型/模式。您可以使用 mongoose-validator ,这只是围绕节点验证器进行简单模型验证的包装器。如果您需要验证其他模型或更复杂的验证逻辑,您可以编写自己的自定义mongoose预验证或后验证钩子(查看mongoose中间件)。
使用mongoose验证您的模型时获得的另外一个好处是,mongoose会向您的模型添加一个错误属性,可以通过 model.errors [属性]
。该属性可用于网络或服务客户端上的验证错误消息。
当编写更多/非常复杂的软件将验证绑定到模型可能会成为问题。但是,当我出现这个问题时,我会处理这个问题。由于JavaScript具有作为一流公民的功能,因此即使在复杂的情况下,您的验证功能仍可重复使用。
Maybe there is not a definitive answer here but I would like to know where to handle data validation when dealing with express.js and mongoose. Which of the following is the best practice (I currently use a combination and it's starting to feel very clumsy):
- the Model (mongoose)
- the Controller / Route (express)
Some older posts I have read are:
but conflicting answers just add to the confusion. Maybe it simply isn't clear cut, in which case is one a better option?
When using mongoose I would push most of my validation logic to the mongoose model/schema. You can use mongoose-validator which is just a wrapper around node-validator for simple model validation. If you need validation against other models or more complex logic in the validation you can write your own custom mongoose pre validate or post validate hook (see mongoose middleware).
An additional benefit you gain when using mongoose to validate your model is that mongoose adds an error property to your model which can be accessed via model.errors[property]
. This property can be used for validation error messages on the web or for a service client.
When writing more/very complex software tying the validation to the model may become a problem. But I'd deal with this problem when it arises. Since JavaScript has functions as first class citizens your validation functions still can be reused even in these complex situations.
这篇关于处理数据验证的最好的地方,用mongoose和express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!