Mongodb mongoose动态附加模式以动态验证
我想根据Mongodb mongoose动态附加模式以动态验证,mongodb,mongoose,Mongodb,Mongoose,我想根据schema.pre('save',function(…){…})中的一些业务逻辑,动态地将一个模式附加到一个特定的字段。如果可能的话,如何做到这一点 一些(简化的)模式和背景: var fact= new Schema({ name: { type: String, required: true, index: { unique: false }} ,value: {type: {}, required: true} ,moreinfodesc: {
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]
从模式的事实可以看出,value
可以有mongoose所关心的任何类型。但是,我希望在运行时将其约束到中定义的模式
FactSchema.valueType
(一个包含“Boolean”、“String”或更复杂的“[Tag]”的字符串)。这可能看起来很麻烦,但出于几个原因,我希望采用这种方式
因此,假设对于具有fact.name=tags
的特定事实,我想在运行时分配fact.value
类型[Tag]
。为此,我会像往常一样设置一个带有验证的Tag
-schema,并对其进行fact.value
验证
我正在考虑以某种方式将[Tag]
-schema“附加”到fact.pre中的fact.value
('save',function(…){..//validation here})
,希望验证会像fact一样神奇地发生。value
在设计时而不是在运行时被分配类型[Tag
最后一个问题是:我不知道是否有可能实现“附加”,如果有,如何实现
谢谢。运行时无法“附加”,但您可以将自定义验证器添加到路径中,并基于当前文档状态建立其逻辑:
尝试使用
如果需要,您可以在运行时使用以下方法更改验证:
YourModelName.schema.path('your_field_name').required(false);
谢谢Aaron,Mongoose是很棒的东西!。与此同时,我找到了使用Mongoose的“动态”模式的解决方案。我调用了类似于
fact.set('value',vals,multivalued?[onTheFlySchema]:onTheFlySchema)的东西
在调用fact.save
之前。这非常有效,包括在eflyschema上的上设置的所有验证和挂钩。建议:您可能想宣传“动态”模式更多一点,它们太棒了!)