如何在 Mongoose 模型中添加不同尺寸的产品?

How to add different sizes of a product in Mongoose model?

我正在使用 MongoDb 和 Mongoose 为练习电子商务网站创建模型。到目前为止,这是我的产品模型:

var mongoose = require('mongoose');

module.exports = mongoose.model('Product',{
  imagePath: {type: String, required: true},
  title: {type: String, required: true},
  description: {type: String, required: true},
  price: {type: Number, required: true}
});

我的问题是我有一件 T 恤有不同尺码选项,例如 S、M 和 L。添加它的最佳方法是什么?另外,如果我包括库存跟踪,我将如何跟踪所有尺寸?在此先感谢您的帮助,我们将不胜感激。

有很多不同的方法可以做到这一点,但最简单的可能是通过一些子模式。例如,您可以创建如下内容:

const ProductVariant = new mongoose.Schema({
  name: String,  // If you're certain this will only ever be sizes, you could make it an enum
  inventory: Number
});

然后在您的产品定义中:

module.exports = mongoose.model('Product',{
  imagePath: {type: String, required: true},
  title: {type: String, required: true},
  description: {type: String, required: true},
  price: {type: Number, required: true},
  variants: [ProductVariant]
});

如果需要,您还可以加入一些逻辑以确保每个产品的变体名称是唯一的,等等,但这是一个基本的实现。

I think this can be a better way

var mongoose = require('mongoose');

module.exports = mongoose.model('Product',{
imagePath: {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required: true},
size:{type:String, enum:["S","M","L"]}
});

创建 Sub Schema 的效率很高,但这里只是为了一个参数,没用。