I’m building a Node.js application using MongoDB and Mongoose. I have a ‘companies’ collection with the following schema:
// app/schemas/company.js
const AboutScheme = new Schema({
slogan: String,
description: String,
});
const CompanySchema = new Schema({
name: String,
about: AboutScheme,
status: String,
user: ObjectId,
email: String
});
I’m creating a POJO class to represent a company document. I want this class to handle its own methods and delegate other methods to the underlying Mongoose document.
// app/domains/company.js
class Company {
constructor(document) {
this.#document = document;
}
sendEmail() {
console.log('sending email...');
}
toJSON() {
return this.#document.toObject();
}
}
The idea is to separate data logic from business logic. But do it transparently for the user:
const CompanyModel = mongoose.model('Company');
const companyDocument = CompanyModel.findOne({ email: '[email protected]' });
const company = new Company(companyDocument);
company.sendEmail(); // handled by Company class
company.name = 'New Name'; // delegated to this.#document
company.about.slogan = 'new slogan'; // deegated to this.#document
company.save(); // delegated to this.#document
I’m trying to use a Proxy to achieve this transparent delegation, but I’m facing some issues. This doesn’t give me access to this.#document and doesn’t have the effect of modifying properties within the document when saving (this.#document.about.slogan) among other issues.
class Company {
#document;
constructor(document) {
this.#document = document;
return new Proxy(this, {
get(target, name, receiver) {
if (self[name]) {
return self[name];
}
return Reflect.get(target, name, receiver);
},
set(target, name, value, receiver) {
return Reflect.set(target, name, value, receiver);
}
});
}
}
Can you help me implement a solution that effectively separates data logic from business logic?