Exploring a few advanced features in Mongoose

Mongoose not only provides convenience methods for CRUDing documents, but it also offers a number of convenient functionalities. We will now use modified snippets from the meanshop/server/api/user/user.model.js project to explain some concepts.

Instance methods

Instance methods are custom methods that we can add to our schemas. They become available at the instance level. For example:

UserSchema.methods.authenticate = function(plainText) {
  return this.encryptPassword(plainText) === this.hashedPassword;
}

The keyword this allows us to access the schema properties and other instance methods. We can use instance methods only in the instances of the model, such as the following code:

var User = mongoose.model('User', ...

Get Web Application Development with MEAN now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.