我需要在猫鼬中使用 @hapi/joi 吗? [英] Do I need to use @hapi/joi with mongoose?

查看:77
本文介绍了我需要在猫鼬中使用 @hapi/joi 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用@hapi/joimongoose?

据我所知 @hapi/joi 用于验证 HTTP 请求(标头、参数、正文等).@hapi/joi 提供它自己的模式验证.mongoose 也提供了它自己的模式验证,但在另一个层面上.如果 hapi/joi 尝试验证 HTTP 请求,则 mongoose 模式验证可确保数据插入到数据库中是有效的.

As I understand @hapi/joi is used for validating HTTP request (headers, parameters, body etc.). @hapi/joi provides it's own schema validation. The mongoose also provides it's own schema validation but on another level. If hapi/joi tries to validate HTTP request, than mongoose schema validation ensures that data is valid to be inserted into the database.

正如您所看到的,这两个库都提供了自己的模式验证(在不同级别上).它需要额外的资源来保持两个架构彼此相等(这是一个错误的地方).

As you can see both libraries provide it's own schemas validation (on different levels). It requires additional resource to keep both schema equal to each other (which is a place for bugs).

问题是:我是否需要同时保留这两个库并支持两种模式?或者我可以使用 mongoose 和它们的验证并且 @hapi/joi 是冗余的?

The question is: Do I need to keep this both libraries and support two schema? Or I can use mongoose and their validation and @hapi/joi is redundancy?

提前致谢!

更新:

我发现了相关问题,但无论如何它都没有回答我的问题:(

I found related question, but it is not answering my question anyway :(

推荐答案

您不必使用像 Joi 这样的架构验证包.

You don't have to use a schema validation package like Joi.

但最好同时使用它们.他们互相称赞.

But it would be good to use both of them. They compliment each other.

Joi 用于 API 以确保客户端发送的数据有效.并且 mongoose 模式用于确保我们的数据处于正确的形状.

Joi is used for APIs to make sure that the data the client sends is valid. And mongoose schema is used to ensure that our data is in right shape.

使用 Joi 进行 API 验证有意义的场景:

A scenario where API validation with Joi makes sense:

我们通常会散列用户密码,因此在我们的用户架构中,密码的 maxlength 选项可能比实际密码长度大得多.因此,使用 Joi,我们可以验证密码字段,使其在登录路径中不能超过例如 10 个字符.

We generally hash the user password, so in our user schema the maxlength option of the password can much bigger than the actual password length. So with Joi we can validate the password field so that it can't be greater than for example 10 characters in a login route.

猫鼬模式验证有意义的场景:

A scenario where mongoose schema validation makes sense:

假设客户端发送了一个有效数据,可能是我们在创建文档时忘记设置属性.如果我们在该字段的 mongoose 模式中没有 required: true 选项,则将在没有该字段的情况下创建文档.

Let's say the client sent a valid data, it is possible that we forgot to set a property when we create a document. If we hadn't a required: true option in the mongoose schema for that field, the document would be created without that field.

在访问数据库之前尽快验证客户端数据有利于安全和性能.

Also validating the client data as soon as possible is good for security and performance before hitting the database.

使用两者的唯一缺点是一些验证重复.但似乎他们创建了一个名为 joigoose 的包来从 Joi 模式创建一个猫鼬模式.

The only downside of using both is some validation duplication. But it seems they created a package called joigoose to create a mongoose schema from a Joi schema.

这篇关于我需要在猫鼬中使用 @hapi/joi 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆