使用Mongoose操作MongoDB时如何实现商品无需子分类即可正常入库
解决方案
你只需要对Product Schema做核心调整,即可满足需求:
1. 修改Product Schema字段配置
首先你需要给商品新增直接关联一级分类的Category字段(避免没有子分类时,商品无法关联到一级分类),同时将原有的SubCategory字段改为非必填、默认值设为null:
const productSchema = mongoose.Schema({ name: { type: String, required: true, }, description: { type: String, required: true }, price : { type: Number, default:0 }, // 新增直接关联一级分类的必填字段 Category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: true }, // 修改子分类为非必填,默认值为空 SubCategory: { type: mongoose.Schema.Types.ObjectId, ref: 'SubCategory', required: false, default: null }, countInStock: { type: Number, required: true, min: 0, max: 255 }, })
2. 可选:添加数据一致性校验
如果需要避免出现「子分类所属的一级分类和商品绑定的一级分类不一致」的异常数据,可以给Schema新增pre保存钩子做校验:
productSchema.pre('save', async function(next) { // 如果填了子分类,校验子分类所属的一级分类和商品绑定的一级分类是否一致 if (this.SubCategory) { const subCategory = await mongoose.model('SubCategory').findById(this.SubCategory); if (subCategory && subCategory.Category.toString() !== this.Category.toString()) { return next(new Error('子分类所属的一级分类与商品绑定的一级分类不匹配')); } } next(); })
3. 业务逻辑适配
后续查询时可以按以下规则处理:
- 筛选某一级分类下的所有商品:直接匹配
Category字段即可,无需关心是否有子分类 - 筛选某子分类下的商品:匹配
SubCategory等于对应ID即可 - 列表展示时,如果
SubCategory为null就只展示一级分类名称,否则展示两级分类名称
内容的提问来源于stack exchange,提问作者user10033434
相关产品推荐
相关产品推荐

