Mongoose allows us to create schema from an ES6 class. 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));

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