How to use ES6 classes to create Mongoose schemas

Mongoose allows us to create a schema from ES6 classes. The loadClass() method provided by Mongoose Schemas takes in a class object as input and copies all methods, statics, and getters/setters of the class into the Schema object.

A ES6 class method maps to a schema method, a static method maps to a schema static method, and getters/setters map to Mongoose virtuals.

To see how it works, let us first define a new ES6 class:

class User {
    set name(name) {
        const tokens = name.split(' ');
        this.firstName = tokens[0];
        this.lastName = tokens[1];
    }

    get name() {
        return `${this.firstName} ${this.lastName}`;
    }

    static findByLastName(lastName) {
        return this.find({ lastName: new RegExp(lastName, 'i') });
    }
}

You can now use the loadClass() method to pull in methods, statics, and getters/setters from the User class into a Mongoose schema:

const schema = new Schema({
    firstName: String,
    lastName: String
});

schema.loadClass(User);

console.log(schema.methods);    // {}
console.log(schema.statics);    // { findByLastName: [Function: findByLastName] }
console.log(schema.virtuals);   
// {
//     name: VirtualType {
//       path: 'name',
//       getters: [ [Function: get name] ],
//       setters: [ [Function: set name] ],
//       options: {}
//     }
// }

As you can see above, we have used an ES6 class to add static and virtual methods to a Mongoose schema. Using the ES6 class notation makes your code easier to read and maintain, especially when you need to add a lot of methods, statics, and virtuals to a schema.

After the import is finished, you can define a model and start writing different queries:

const Person = mongoose.model('Person', schema);

// Create new document
const alex = new Person({ name: 'Alex Jones' });
// { _id: 5fe6521b6fe6a151b56104c4, firstName: 'Alex', lastName: 'Jones' }

// Fetch documents by the last name
Person.findByLastName('Shah')
    .then(docs => console.log(docs))
    .catch(err => console.log(err));

Read this guide to learn more about classes in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.