我对我的收藏设计有个问题。
电流设计
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“的目的是让他们检查自己的历史。
这是个好主意吗或者,如果你有一个好的主意,请少免费分享。
谢谢
发布于 2021-12-14 08:22:47
我已经创建了两种不同的模式,一个用于客户,另一个用于购买。
请按照标准程序将所有服务文件、模型文件、控制器文件保存在单独的文件夹中。
以下是客户模型。
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;
}
};这里遵循的设计原则是按照高级开发人员的建议避免重复。在不同的集合中存储相同的值是不好的做法,因为购买数据存储在客户集合中。
https://stackoverflow.com/questions/70345194
复制相似问题