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(a String contains "Boolean", "String" 或更复杂的 "[Tag]") 中定义的模式。这可能看起来很麻烦,但这是我想走的路,原因有几个。

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

我正在考虑以某种方式将[Tag]-schema “附加”到fact.valueinfact.pre('save',function(..){.. //validation here })并希望验证会神奇地发生,就好像在设计时而不是运行时fact.value分配了类型一样。[Tag]

最后一个问题:我不知道是否可以进行“附加”,如果可以,怎么做?

谢谢。

4

2 回答 2

1

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

https://gist.github.com/2789681

于 2012-05-25T18:27:45.367 回答
0

尝试使用猫鼬鉴别器 如果需要,您可以在运行时更改验证:

YourModelName.schema.path('your_field_name').required(false);
于 2019-03-11T08:47:27.870 回答