
Mongoose is an Object Relational Model (“ORM”).
It allows you to communicate with your database using objects and classes.
A Mongoose-like ORM simplifies the database operations and provides an abstraction layer between your application code and the database instead of writing raw SQL queries.
In this post, we mainly focus on how to create a simple schema in Mongoose.
Install
Before using Mongoose we need to connect our database to our ExpressJs application.
In my previous post, I already covered how to create and connect a database to an express app, you can check via this link.
After you set up a database you can install Mongoose by this npm command.
npm install mongoose
In-build validations in Mongoose
In Mongoose schema we can use in-build validations to ensure that data stored in your MongoDB database meets the given criteria.
These are some examples of inbuild validations in Mongoose.
required: trueunique: true
Data types in Mongoose
In Mongoose, data types are used to define the structure and type of data that can be stored in MongoDB documents.
Here are some commonly used data types with examples.
You can use these data types based on your Schema model requirements.
- String:
'John Doe' - Number:
42 - Date:
new Date() - Mixed:
{ anyField: 'anyValue' } - Boolean:
true - ObjectId:
mongoose.Types.ObjectId('609fb2367e33ad001ef24985') - Buffer:
Buffer.from('Hello World') - Array:
['apple', 'banana', 'orange']
Virtual Properties
Sometimes we need to play around with schema properties but that does not need to be stored on the database itself.
For that purpose, we can use the Virtual Properties concept in Mongoose.
Virtual Properties are not stored in the database but can be accessed when querying the database.
Following is a simple use case of Virtual Properties. We are just combining the title + author to form a new schema property called fullName.
BookSchema.virtual("fullName").get(function () {
return this.title + " by " + this.author;
});
# Conclusion
In this blog, we covered how to get started with `Mongoose` ODM in an ExpressJS app by creating a simple `BookSchema` model and we created a `post` endpoint to create a new book.
You can check the official Mongoose [documentation](https://mongoosejs.com/docs/) for more information.
Happy learning/coding 😎