【问题标题】:Node JS Model with inner/nested array具有内部/嵌套数组的节点 JS 模型
【发布时间】:2022-01-17 13:08:17
【问题描述】:

我对我的收藏设计有疑问。

目前的设计

const customerSchema = mongoose.Schema({
customer_name: {
    type: String
},
purchase_history: [{
    amount: {
        type: Number,
        default: 0
    },
    currency: {
        type: String,
        require: true
    },
    description: {
        type: String
    }
}],
......
});

客户每次购买新商品时,都会将历史推送到“purchase_history”中。

“purchase_history”的目的是让他们检查自己的历史记录。

这是个好主意吗?或者如果您有好主意,请免费分享。

谢谢

【问题讨论】:

    标签: node.js arrays mongodb database-design


    【解决方案1】:

    我创建了 2 种不同的模式,一种用于客户,另一种用于购买。

    请按照标准程序将所有服务文件、模型文件、控制器文件保存在单独的文件夹中。

    下面是客户模型。

    customer.model.js

    const mongoose = require('mongoose');
    let Schema = mongoose.Schema;
    
    const CustomerSchema = mongoose.Schema({
      customer_name: {
        type: String,
      },
    });
    
    const customer = mongoose.model('customer', CustomerSchema);
    module.exports = customer;
    

    我们的购买模式为:

    purchase.model.js

    const mongoose = require('mongoose');
    let Schema = mongoose.Schema;
    const customer = require('./customer.model');
    
    var purchaseSchema = new Schema(
      {
        customerId: { type: Schema.Types.ObjectId, ref: 'customer' },
        amount: {
          type: Number,
          default: 0,
        },
        currency: {
          type: String,
          required: true,
        },
        description: {
          type: String,
        },
      },
      { timestamps: true }
    );
    
    module.exports = mongoose.model('purchase', purchaseSchema);
    

    在这里,我们可以看到客户数据存储在客户集合中,购买数据存储在购买集合中。

    每条购买记录都有一个参考字段“customerId”,这是客户的唯一标识符。该字段在购买模型中定义。

    可以通过查询customerId字段来获取客户的购买历史。

    我们可以创建一个用于获取客户购买的 api:

    purchase.service.js

    const purchaseModel = require('./purchase.model');
    
    module.exports.getByCustomerId = async (_customerId) => {
      try {
        const purchaseList = await purchaseModel.find({
          customerId: _customerId,
        });
        return purchaseList;
      } catch (err) {
        throw err.message;
      }
    };
    
    

    这里遵循的设计原则是按照高级开发人员的建议避免重复。将相同的值存储在不同的集合中并不是一个好习惯,购买数据存储在客户集合中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2018-05-11
      • 1970-01-01
      • 2019-02-04
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多