Creation method in Mongoose.js, alternative to custom constructor or hooks

Creation method is a neat way of creating objects in the same way by using the object's well-named static method instead of constructor. While similar, creation method should not to be confused with factory method pattern, which involves the concrete implementation of created objects). If you'd like to know more about creation method's benefits and application I highly recommend Joshua Kerievsky's Refactoring to Patterns.

Here's how this alternative to custom constructor or hooks can work in Mongoose.

Let's use an Article model in Mean.js app generated by Yeoman as an example:
Let's say we'd like article to have an url field, which we'd like to generate from the title. We'd like to avoid copying the url generation code everytime we'd like to create an article. One way to do this is to create a creation method which does that.
Since all static methods have to be defined before the model class is created creating a creation method the following won't work:
Instead we can simply fetch the model using mongoose.model. Here's a working example of a creation method:

Comments

Popular posts from this blog

Setup SQL Server 2012 and Adventure Works cube with Visual Studio 2010

Installing FANN on Java project and NativeLibrary.loadLibrary problems with 32bit/64bit

MongoDB and distinct values in arrays