Using ES6 Classes with Schemas in Mongoose
Mongoose supports defining schemas using ES6 classes through the loadClass() method. This allows you to use modern JavaScript class syntax to define instance methods, static methods, and virtual properties in a clean and organized way, improving maintainability and readability.
Table of Content
What is loadClass()?
The loadClass() method allows you to take an ES6 class and load its instance methods, static methods, and getters/setters as Mongoose schema methods, statics, and virtuals respectively.
Defining an ES6 Class for a Schema
Define the schema fields normally and then create an ES6 class with your methods:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
firstName: String,
lastName: String
});
class UserClass {
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
set fullName(name) {
const split = name.split(' ');
this.firstName = split[0];
this.lastName = split[1];
}
getFullName() {
return this.fullName;
}
static findByLastName(lastName) {
return this.find({ lastName });
}
}
Mapping Class Methods and Virtuals to Schema
Use schema.loadClass() to map the class to the schema:
userSchema.loadClass(UserClass);
const User = mongoose.model('User', userSchema);
Example Usage
Creating and using documents with ES6 class methods and virtuals:
async function example() {
const user = new User({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName); // John Doe
user.fullName = 'Jane Smith';
console.log(user.firstName); // Jane
console.log(user.lastName); // Smith
console.log(user.getFullName()); // Jane Smith
const found = await User.findByLastName('Smith');
console.log(found);
}
example();
Advantages of Using ES6 Classes
- Cleaner, more maintainable code using standard JavaScript class syntax.
- Group related methods, statics, and virtuals inside a single class.
- Leverages modern JavaScript features for better readability.
- Easy to extend and reuse via class inheritance.
Best Practices
- Define schema fields separately;
loadClass()loads only methods and virtuals. - Use ES6 classes to organize complex schemas with many methods or statics.
- Keep business logic encapsulated within class methods for cleaner architecture.
- Combine with TypeScript for type safety in modern applications.
Conclusion
Using ES6 classes with Mongoose schemas via the loadClass() method offers a modern and elegant approach to defining methods, statics, and virtuals. This promotes better organization, coding standards, and maintainability in your Node.js and MongoDB applications.
Comments
Post a Comment