【问题标题】:MongoDB database design for products and bundles产品和捆绑包的 MongoDB 数据库设计
【发布时间】:2017-06-01 15:16:56
【问题描述】:

我正在尝试使用 mongoDB 数据库构建一个基于 Node.js 的电子商务网站,但我遇到了一些数据库设计或我缺少的一些逻辑方面的问题

总而言之,我有 Product 包含价格、名称、描述等...和 ​​Bundle 包含一系列产品(通过引用)。主要问题是当我必须订购时,我无法将ProductBundle 放在一起......

所以我已经有了Product 架构:

const productSchema = new mongoose.Schema({
  file: {
    type: String,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  preparation: String,
  allergics: {
    type: Array,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  // More fields
});

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

还有一个 Bundle 架构,其中包含对 Product 的引用(一个捆绑包包含多个产品):

const bundleSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  itemsId: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product',
    required: true,
  }],
  description: String,
  reduction: {
    type: Number,
    min: 0,
    default: 0,
    max: 100,
  },
});

module.exports = mongoose.model('Bundle', bundleSchema);

因此,当用户订购捆绑包或单个产品时,我使用此模式:

const orderSchema = new mongoose.Schema({
  orderedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  articlesId: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Product',
    },
  ],
  itemsNumber: {
    type: Array,
    required: true,
  },
  amount: Number,
  orderedAt: Date,
  placeToShip: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Place',
  },
});

module.exports = mongoose.model('Order', orderSchema);

如您所见,我只引用 Product ,但我想引用 Product AND Bundle ,我不知道这是否可能,或者这是否是错误的设计方式像这样的数据库。

对不起,如果帖子有点长,但我会尽量清楚!非常感谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    如果您想在articleId 中引用productbundle(取决于用户购买捆绑或单品),您可以这样做:

    不要在orderSchemaarticleId 字段中提供ref,只需将其type 指定为ObjectId

    const orderSchema = new mongoose.Schema({
      ...
      articlesId: [
        {
          type: mongoose.Schema.Types.ObjectId
        },
      ],
      ...
    });
    

    并且,在填充时告诉它从哪个modelpopulate

    //In case user bought a product
    Order.find({findQuery})
         .populate({path : '',model : 'Product'})
         .exec(function(err,result){...});
    
    //In case user bought a Bundle
    Order.find({findQuery})
         .populate({path : '',model : 'Bundle'})
         .exec(function(err,result){...});
    

    但是,您必须有办法找出user 购买了单曲productbundle。 希望对你有帮助!

    【讨论】:

    • 好的,非常感谢,我今晚会试试这个,让您了解最新情况!
    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2013-07-01
    • 2014-02-12
    相关资源
    最近更新 更多