如何定义与mongodb中的产品链接的产品变体模式?

问题描述 投票:0回答:1

我正在尝试构建电子商务系统,我有 Product 和 ProductVariant 架构,如下所示:

import mongoose from "mongoose";
const { Schema } = mongoose;

// Schema for each variant option (e.g., "Size", "Color")
const VariantOptionSchema = new Schema({
  variantName: { type: String, required: true },  // e.g., "Size", "Color"
  option: { type: String, required: true },       // e.g., "Large", "Red"
});

// Schema for combinations of variant options
const ProductVariantSchema = new Schema({
  options: [VariantOptionSchema],                // e.g., [{variantName: "Size", option: "M"}, {variantName: "Color", option: "Red"}]
  price: { type: Number, required: true },       // Price for this combination
  stock: { type: Number, required: true },       // Stock for this combination
});

// Product schema with variants
const ProductSchema = new Schema(
  {
    name: { type: String, required: true },
    description: { type: String },
    basePrice: { type: Number, required: true }, // Base price without variants
    category: { type: String, required: true },
    variants: [ProductVariantSchema],            // Array of variant combinations
    images: [{ type: String }],                  // Array of image URLs
    brand: { type: String },
    stock: { type: Number },                     // Base stock if no variants are present
  },
  { timestamps: true }
);

// Creating the Product model
const Product = mongoose.model("Product", ProductSchema);
export default Product;

但是我在这个模式上看到的主要挑战是,尽管它提供了为特定产品添加不同变体的灵活性,如果不同的用户添加像Size:Large vs Size:L这样的变体,它可能会导致过滤或搜索时不一致通过变体。这可能会导致难以为客户提供准确的过滤器,并且如果命名约定不同,某些变体可能无法正确显示。因此,特定产品不会有固定的变体,就像我们看到的计算机等产品一样,变体是固定的,例如大小、RAM、存储等...... 那么有没有办法解决这个问题,尽管它提供了灵活性?

node.js mongodb mongoose
1个回答
0
投票

为了确保添加产品的所有用户的尺寸部分保持相同,您可以使用

enum
。通过这种方式,您可以限制用户添加任何随机尺寸,并且只允许他们添加您提供的尺寸。所以现在,如果用户想要添加L尺寸,则需要选择“Large”。如果未选择,或传递了错误的值,您可以验证并抛出错误。

猫鼬中的枚举

© www.soinside.com 2019 - 2024. All rights reserved.