Programming Blog

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

 

Create a Mongoose schema

In Mongoose, a model schema represents a collection in the database and provides an interface for creating, reading, updating, and deleting documents.

We are going to create a simple BookSchema with title, author, genre, publishedYear, isBestseller as its properties.

// models/book.js
const mongoose = require("mongoose");

const BookSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
		unique: true,
  },
  author: {
    type: String,
    required: true,
  },
  genre: {
    type: String,
    required: true,
  },
  publishedYear: {
    type: Number,
    required: true,
  },
  isBestseller: {
    type: Boolean,
    required: false,
    default: false,
  },
});

const Book = mongoose.model("Book", BookSchema);

 

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.

  1. required: true

  2. unique: 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.

  1. String: 'John Doe'
  2. Number: 42
  3. Date: new Date()
  4. Mixed: { anyField: 'anyValue' }
  5. Boolean: true
  6. ObjectId: mongoose.Types.ObjectId('609fb2367e33ad001ef24985')
  7. Buffer: Buffer.from('Hello World')
  8. 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;
});

You can use this fullName on your front end same as BookSchema properties.

Key concepts to remember

  1. This fullname is not actual property for BookSchema and thus this will not be stored in the database.
  2. You need to add the following code on the same model file where you initiated your BookSchema order to use the Virtual Property.

 

Use the schema in your Express.js

This following code sets up an Express.js server, defines a route for creating a new book, saves the book to the database using Mongoose, and sends a response back to the client with the saved book object.

// server.js
const express = require("express");
const app = express();
const Book = require("./models/book");

app.post("/create-book", async (req, res) => {
  const book = new Book({
    title: "The Almanack of Naval Ravikant",
    author: "Eric Jorgenson",
    genre: "Finance",
    publishedYear: 2020,
  });

  await book.save();
  res.status(201).send(book);
});

app.listen(3000, () => console.log("Server started on port 3000"));

 

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 for more information.

Happy learning/coding 😎