首页 文章

mongoose动态附加模式以在运行中进行验证

提问于
浏览
0

我想根据 schema.pre('save',function(..){...}) 中的一些业务逻辑动态地将模式附加到特定字段 . 如果可能的话怎么做?

一些(简化的)模式和背景:

var fact= new Schema({  
    name: { type: String, required: true, index: { unique: false }}
    ,value: {type:  {}, required: true}  
    ,moreinfodesc: { type: String, required: false} 
    ,createddate : { type: Date, required: true, default: Date.now, select: false } }
}, { collection: 'Fact' } );

var factSchema= new Schema({
    name: { type: String, required: true, index: { unique: true }}
    , valueType: { type: {}, required: true}                                        
    ,isMulti: {type: Boolean, required: true }

    //ACL-stuff
    ,directChangeRoles: {type: [String]} //i.e: [super, admin,owner]
    ,suggestChangeRoles: {type: [String]} //ie: [editor]
    ,enum: {type: [{}]} 
    ,mixins: {type: [String]} 
}, { collection: 'FactSchema' });

这是一种简化的结构,允许编辑特定“实体”的“事实” .

e.g: entityA.facts=[fact]

从架构中可以看出,就猫鼬而言, fact.value 可以有任何类型 . 但是,我希望在运行时将它约束到 FactSchema.valueType 中定义的模式(包含"Boolean","String"的字符串或更复杂的"[Tag]") . 这可能看起来很麻烦,但这是我想要出于几个原因的方式 .

所以,假设对于 fact.name=tags 的特定事实,我想在运行时分配 fact.value 类型 [Tag] . 为此,我会像往常一样设置一个 Tag -schema验证并对它进行 fact.value 验证 .

我正在考虑以某种方式"attaching" fact.value fact.value fact.pre('save',function(..){.. //validation here }) 并希望验证会神奇地发生,好像 fact.value 在设计时被分配了类型 [Tag] 而不是运行时 .

最后一个问题:我不知道是否有可能做'附加',如果是这样,怎么样?

谢谢 .

1 回答

  • 1

    在运行时“附加”是不可能的,但您可以在路径中添加自定义验证器,并将其逻辑基于当前文档状态:

    https://gist.github.com/2789681

相关问题