Javascript 在mongodb的1个变量下定义2个类型
我正在尝试创建一个如下所示的模式:Javascript 在mongodb的1个变量下定义2个类型,javascript,database,mongodb,mongoose,Javascript,Database,Mongodb,Mongoose,我正在尝试创建一个如下所示的模式: const exampleSchema = mongoose.Schema({ topic: { type: String, required: true, }, words: { type: String || Array: { type: String, required: true, }
const exampleSchema = mongoose.Schema({
topic: {
type: String,
required: true,
},
words: {
type: String || Array: {
type: String,
required: true,
}
required: true,
}
});
我已经阅读了mongodb中的自定义类型,但不理解文档中显示的内容。有人能帮我吗?在猫鼬中创作
class StringOrArray extends mongoose.SchemaType {
constructor(key, options) {
super(key, options, 'StringOrArray');
}
cast(val) {
// please change your logic as per your requirement
if (typeof val !== 'string' && !Array.isArray(val)) {
throw new Error('StringOrArray: ' + val + ' must be a String or Array');
}
return val;
}
}
// Don't forget to add `Int8` to the type registry
mongoose.Schema.Types.StringOrArray = StringOrArray;
在模式中使用stringorary
const exampleSchema = mongoose.Schema({
topic: {
type: String,
required: true,
},
words: {
type: StringOrArray,
required: true
}
});
这回答了你的问题吗?很遗憾,是的,但对我来说太复杂了。我不知道如何创建它,也不知道它是如何工作的。我编辑了我的问题,希望有人能帮助我!