【问题标题】:How to add different sizes of a product in Mongoose model?如何在 Mongoose 模型中添加不同尺寸的产品?
【发布时间】:2017-10-22 03:03:47
【问题描述】:

我正在使用 MongoDb 和 Mongoose 为实践电子商务网站创建模型。到目前为止,我的 Product 模型如下所示:

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}
});

我的问题是说我有一件衬衫,它有不同的尺寸可供选择,例如 S、M 和 L。添加它的最佳方法是什么?此外,如果我包括库存跟踪,我将如何跟踪所有尺寸?在此先感谢您的任何帮助。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

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

    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]
    });
    

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

    【讨论】:

      【解决方案2】:

      我认为这可能是一个更好的方法

      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"]}
      });
      

      创建子架构很有效,但这里只是为了一个参数,没用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-10
        • 1970-01-01
        • 2021-10-08
        • 2020-10-08
        • 2013-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多