gpt4 book ai didi

node.js - 如何通过 Joi.validate 验证数据库中的唯一性?

转载 作者:行者123 更新时间:2023-12-04 17:43:51 35 4
gpt4 key购买 nike

是否可以将函数插入到 Joi 验证模式中,如果值是唯一的,该模式将检查数据库?

(检查将由我在 Joi 函数方法中创建的函数完成)。

也许是这样的:

phone: Joi.customCheck(function(v) {
let bool;
// check in DB if v is already exists, then assign the value to bool...
return bool;
}).required()

我在 Google 和 Joi api 引用中进行了搜索,但一无所获。

最佳答案

您可以使用新函数 any().external()(自版本 16.0.0 起)。这可用于进行数据库查找。

const lookup = async (id) => {

const user = await db.get('user', id);
if (!user) {
throw new Error('Invalid user id');
}
};

const schema = Joi.string().external(lookup);
await schema.validateAsync('1234abcd');

关于node.js - 如何通过 Joi.validate 验证数据库中的唯一性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154304/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com