mongodb 中的类别和子类别使用 mongoose

Category and Subcategory in mongodb using mongoose

我正在使用 nodejs 创建一个电子商务网站。理想情况下,产品将具有类别和子类别。但是我创建的内容应该用于任何类型的电子商务网站,因此可能不需要子类别字段。

在产品架构中,我添加了与子类别文档相关的子类别字段。并且子分类文档与分类文档相关。

我的问题是,没有子类别的产品如何添加到数据库中?

类别架构:

const categorySchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    }
})

module.exports = mongoose.model('Category', categorySchema);

子类别架构:

const subCategorySchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    Category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required:true
    },
})

module.exports = mongoose.model('SubCategory', subCategorySchema);

产品架构:

const productSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    description: {
        type: String,
        required: true
    },
    price : {
        type: Number,
        default:0
    },
    SubCategory: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'SubCategory',
        required:true
    },
    countInStock: {
        type: Number,
        required: true,
        min: 0,
        max: 255
    },
})


module.exports = mongoose.model('Product', productSchema);

提前致谢...

恐怕您的 ProductSchema 中必须有一个必填的 Category 字段和一个非必填的 SubCategory 字段。这样,您将确保您的所有产品至少有一个类别,并允许添加子类别:

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
  },
  countInStock: {
      type: Number,
      required: true,
      min: 0,
      max: 255
  },
})

如果你想确保类别和子类别的层次结构,你总是可以在你的预存中添加一些中间件验证:

productSchema.pre('save', async function (next) {
  if (this.SubCategory) {
    try {
      const check = await SubCategory.findById(this.SubCategory);
      if (!check || JSON.stringify(check.Category) !== JSON.stringify(this.Category)) {
        throw new Error('Check your Category and/or SubCategory');
      }
    } catch (error) {
      throw error;
    }
  }
  next();
});