MongoDB

Mastering Mongoose: Middleware, Validation & Virtuals

S

Sajan Acharya

Author

November 18, 2024
9 min read

Why Mongoose?

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more.

Middleware (Hooks)

Middleware are functions which are passed control during execution of asynchronous functions.

userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 12);
  next();
});

Virtuals

Virtuals are document properties that you can get and set but that do not get persisted to MongoDB.

userSchema.virtual('fullName').get(function() {
  return this.name.first + ' ' + this.name.last;
});

Populate

Mongoose's populate() method lets you reference documents in other collections. It's powerful but use it wisely to avoid N+1 query problems.

Tags

#Mongoose#Node.js#Database#ORM

Share this article

About the Author

S

Sajan Acharya

Content Writer

Passionate about technology and sharing knowledge with the community.

Stay Updated

Get the latest articles delivered to your inbox