Mongoose嵌套模式验证模型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongoose嵌套模式验证模型相关的知识,希望对你有一定的参考价值。
我有以下Mongoose模型:
var schema = mongoose.Schema(
webServiceType: type: String, default: ''
, siteMinder:
site_url: type: String, default: ''
,sso_url: type: String, default: ''
,sso_key: type: String, default: ''
,ad_group: type: String, default: ''
, adfs:
authorize_url: type: String, default: ''
,client_id: type: String, default: ''
,token_url: type: String, default: ''
,callback_url: type: String, default: ''
,redirect_url: type: String, default: ''
);
我需要检查Web服务类型是adfs还是siteminder。如果值是adfs,我需要验证子对象,如authorize_url,client_id等。
我尝试了以下步骤,但收到错误。
schema.path('webServiceType').validate(function(value, next)
if(value == 'adfs')
schema.path('adfs.authorize_url').validate(function(value, respond)
var validation = value.length != 0;
respond(validation);
, 'Invalid Authorize URL');
schema.path('adfs.client_id').validate(function(value, respond)
var validation = value.length != 0;
respond(validation);
, 'Invalid Client ID');
schema.path('adfs.token_url').validate(function(value, respond)
var validation = value.length != 0;
respond(validation);
, 'Invalid Token URL ');
schema.path('adfs.callback_url').validate(function(value, respond)
var validation = value.length != 0;
respond(validation);
, 'Invalid Callback URL');
schema.path('adfs.redirect_url').validate(function(value, respond)
var validation = value.length != 0;
respond(validation);
, 'Invalid ADFS Login Redirect URL ');
next();
);
提前致谢!
答案
如果您需要基于webServiceType
获得不同的验证/不同模式,那么更好的选择是使用鉴别器:
const webServiceSchema = new mongoose.Schema( /* some common part */, discriminatorKey: 'webServiceType');
const WebService = mongoose.model('Event', eventSchema);
const SiteMinder = WebService.discriminator('siteMinder', new Schema(
site_url: type: String, default: '', validate: (value) => value.length != 0,
sso_url: type: String, default: '', validate: (value) => value.length != 0,
sso_key: type: String, default: '', validate: (value) => value.length != 0,
ad_group: type: String, default: '', validate: (value) => value.length != 0
));
const Adfs = WebService.discriminator('adfs', new Schema(
authorize_url: type: String, default: '', validate: (value) => value.length != 0,
client_id: type: String, default: '', validate: (value) => value.length != 0,
token_url: type: String, default: '', validate: (value) => value.length != 0,
callback_url: type: String, default: '', validate: (value) => value.length != 0,
redirect_url: type: String, default: '', validate: (value) => value.length != 0,
));
另请注意,我已将此长度的所有验证移至validate
属性。它似乎更好,你可以读到它here
以上是关于Mongoose嵌套模式验证模型的主要内容,如果未能解决你的问题,请参考以下文章
您如何在 Node.js + Express + Mongoose + Jade 中处理表单验证,尤其是嵌套模型