How to Add Instance Methods with Mongoose
Introduction
If you’re using the popular Schema-Model based library Mongoose to interact with MongoJS from NodeJS then this article will provide you about the basics of instance methods. If you don’t know what an instance method is, we’ll show you, and then you’ll quickly find ways to utilize this functionality because it comes in extremely handy in numerous situations.
Instance Methods
Instance methods are methods that perform some action on a specific instance of a Model rather than the entire Model itself. Methods that perform some action on the entire Model are known as static methods. Static methods are also come in handy in their own share of situations but if you’re looking for some functionality on an individual database entry itself then you’ll be wanting to deal with instance methods.
If the word ‘Instance’ is confusing you, just think about an Instance as a single document because that what it really is. The term instance is common programming terminology but it’s important to not get too wrapped up in terminology and more important to understand the concept.
Demo Examples
We’ll use a common demo of an instance method that clearly exhibits the instance functionality. Let’s assume that we have a collection of Users for which we have created a UserSchema that contains a firstName and a lastName field that are Strings. What if in our code we were frequently concatenating the firstName and lastName to create the full name? This is something an instance method could help with.
To do this we’d create a custom method on our schema that could create the full name for us and it would be available on every instance through the model. Let’s see how we’d do that:
1 2 3 | userSchema.methods.getFullName = function() { return this.firstName + this.lastName } |
Notice how we used the keyword this
which refers to the specific instance of the Model, in this cas it refers to a specific User.
Now let’s see how we’d actually use this instance method:
1 2 3 4 5 6 7 | let model = new UserModel({ firstName: 'Alfred', lastName: 'Tompkins' }) let fullName = model.getFullName() console.log(fullName) // Result: Alfred Tompkins |
Let’s go over a second example to cement our understanding. In this second example we’ll show you the full schema first.
In this example we have a schema representing a grocery store product and we’ll have an instance method on each product that can find products in the same department. Let’s take a look at the productSchema first:
1 | var productSchema = new Schema({ name: String, department: String }); |
Next we define a function on the methods
object of the schema. The function uses the find method to find Products who have a matching department.
1 2 3 | productSchema.methods.findProductsInSameDepartment = function() { return this.model('Product').find({ department: this.department }); }; |
Now we let’s finally use this instance method:
1 2 3 4 5 6 | var Product = mongoose.model('Product', productSchema); var milk = new Product({ department: 'Dairy' }); milk.findProductsInSameDepartment(function(err, dairyProducts) { console.log(dairyProducts); }); |
Conclusion
We hope this short tutorial acquainted you with instance methods in Mongoose and the associated syntax and functionality. We hope you can see the options that instance methods open up and that you can apply them where they fit within your specific application. If you found this type of functionality useful you might want to look into static functions in Mongoose as well to see where you can apply that type of functionality as well. If you have any questions or feedback please don’t hesitate to reach out to us.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started