Separating Mongoose: Schemas, Methods and Statics

Alexander Karan
3/5/2019 | 2 min read

Mongoose makes working with MongoDB easier, and it’s a quicker way to get your NodeJS app up and running with MongoDB. There are pros and cons of using MongooseJS over MongoDB’s Native Node driver, but that is outside the scope of this blog.



Now Swagger has some fantastic documentation but wasn’t so straightforward when setting up with express, so let’s jump straight into it and document our API.

One of the best features about Mongoose is the Methods, Hooks and Statics that you can add to your model, however, I love clean code and small files, and this can easily not be the case once you have added a few hooks or methods. Separating or splitting these when one is in the infancy stages of learning may not be obvious, so let’s have a look with a real-world example.

Here you can see my User Model in the User.js

User.js

When we create a new User in our imagery database at this point, I want to hash the password and save the hash instead. In a new file, I labeled Auth.js I added a pre-hook as you can see below.

Auth.js

Pay attention to how I wrote the pre-hook, this will allow us to add the hook easily back in the User Model file. My overall function takes in the User Schema so that I can add as many hooks, methods or statics inside this function.

User.js

We pass the Schema into the requirement for the Auth file, and now any function added in the Auth file function will be added to our Schema.

One final example to make sure you understand the process, I have added a static method that allows you to authenticate a user. Once again adding it into the overall function in the Auth.js file

Auth.js

As with all programming techniques splitting can be achieved by many other approaches, Dependency Injection is one way but outside the scope of this blog. If you would like a further read on Dependency Injection check out this fantastic blog by Jeff Hansen: dependency-injection-in-node-js