我创建了 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;
}
};
这里遵循的设计原则是按照高级开发人员的建议避免重复。将相同的值存储在不同的集合中并不是一个好习惯,购买数据存储在客户集合中。