如何在Mongoose Schema中实现OR运算符定义多类型组件数组?
解决Mongoose中多类型组件数组的定义问题
你用||运算符的方式是错误的——JS逻辑或只会返回第一个真值Schema,导致数组只能接受heading类型的元素。Mongoose提供了**鉴别器(Discriminators)**来处理同一数组包含不同类型文档的场景,完美匹配你的需求,以下是具体实现方案:
修改后的完整代码
const mongoose = require("mongoose"); // 基础组件Schema,抽取出三个组件的共同字段 const componentSchema = new mongoose.Schema({ componentId: { type: String, required: true, }, }, { discriminatorKey: 'type' }); // 指定type字段作为不同组件类型的区分标识 // 基于基础Schema创建各组件的鉴别器,扩展专属的details字段 const Heading = mongoose.model('Component', componentSchema).discriminator( 'heading', new mongoose.Schema({ details: { content: { type: String, required: true }, fontSize: { type: String, required: true }, fontType: { type: String, required: true }, color: { type: String, required: true }, }, }) ); const Text = mongoose.model('Component', componentSchema).discriminator( 'text', new mongoose.Schema({ details: { content: { type: String, required: true }, lineHeight: { type: String, required: true }, fontType: { type: String, required: true }, color: { type: String, required: true }, }, }) ); const Image = mongoose.model('Component', componentSchema).discriminator( 'image', new mongoose.Schema({ details: { imageName: { type: String, required: true }, imageUrl: { type: String, required: true }, width: { type: String, required: true }, }, }) ); // 网站Schema定义 const websiteSchema = new mongoose.Schema({ name: { type: String, required: true, }, owner: { type: String, required: true, }, components: { type: [componentSchema], required: true, }, }); module.exports = mongoose.model("Website", websiteSchema);
工作原理
- 基础
componentSchema包含所有组件的共同字段(componentId),并通过discriminatorKey: 'type'指定用type字段区分不同组件类型 - 每个组件鉴别器(Heading/Text/Image)基于基础Schema扩展,定义各自专属的
details结构 - 当向
components数组添加元素时,Mongoose会自动根据元素的type值匹配对应的鉴别器,验证该元素的结构是否符合对应组件的规则
内容的提问来源于stack exchange,提问作者youssefrag
相关产品推荐
相关产品推荐

