I have created 2 different schemas, one for the customer and another for the purchase.
Please follow the standard procedure to keep all the service files, model files, controller files in separate folders.
The below is the customer model.
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;
We have the purchase model as:
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);
Here, we can see the customer data is stored in customer collection and the purchase data stored in the purchase collection.
Each purchase record has a reference field 'customerId' which is the customer's unique identifier. This field is defined in the purchase model.
The customer's purchase history can be fetched by querying for the customerId field.
We can create an api for fetching customer's purchases as:
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;
}
};
The design principle followed here is to avoid duplication as suggested by a Senior developer. It is not good practice to store the same value in different collections, the purchase data being stored in the customer collection.