我正在尝试创建动态猫鼬模式。 父模式是“接口”。这有两个字段:“类型”和“设置”。
基于提交的“类型”,我需要创建/分配/验证“设置”字段。
const ENUM_SETTINGS = {
"RS232": new mongoose.Schema({
baudRate: {
type: Number,
required: true
},
dataBits: {
type: Number,
default: 8
},
stopBits: {
type: Number,
default: 1
},
parity: {
type: String,
enum: ['none', 'even', 'mark', 'odd', 'space'],
default: "none"
},
rtscts: {
type: Boolean,
default: false
},
xon: {
type: Boolean,
default: false
},
xoff: {
type: Boolean,
default: false
},
xany: {
type: Boolean,
default: false
}
}),
"ETHERNET": new mongoose.Schema({
host: {
type: String,
required: true
},
port: {
type: Number,
required: true
},
path: {
type: String,
default: "/"
},
protocol: {
type: String,
required: true,
enum: ["ws", "http", "tcp", "udp"]
}
})
};
const interfaceSchema = new mongoose.Schema({
type: {
type: String,
required: true,
enum: Object.keys(ENUM_SETTINGS)
},
description: {
type: String
},
adapter: {
type: ObjectId,
ref: "Adapters",
//required: true
},
settings: {
type: mongoose.Schema.Types.Mixed,
required: true,
// ... ENUM_SETTINGS based on type value
}
}, {
strict: false
});
如果在“ interfaceSchema”上使用的“类型”是“ ETHERNET”,则应将ENUM_SETTINGS["ETHERNET"]
用作“设置”字段。
“ RS232”也一样,然后
ENUM_SETTINGS["RS232"]
应该使用
我要使用模式的原因是,它没有内置的验证器,我不需要在自定义验证器或我的业务逻辑中对其进行检查。
我在猫鼬文档中读到的内容,当创建我的架构时,为时已晚,不能做类似的事情...
是否有一种变通方法或简便的方法来验证ìnterface.settings中的给定数据对我的ENUM_SETTINGS[<type>]
模式的影响?