LogoLogo
  • Introduction
  • Backend
    • Creating a MongoDB Database
    • Environment Variables
    • Configuring the Mailing Service
    • Seeding the Database
    • Starting the Backend
  • Frontend
    • Starting the Frontend
  • Book Module Tutorial
    • Introduction
    • Backend
      • Create Model
      • Create Service
      • Create Route
      • Test using Postman
    • Frontend
      • Introduction
      • File Structure
      • Defining Concepts
      • Display App in Dashboard
      • Create Module
      • Create Book List Component
      • Create Main Component
      • Create Service
      • Display Book List
      • Add a Book
        • Update Service
        • Create Component
        • Final Code Review
      • Delete a Book
        • Update Service
        • Update Component
        • Final Code Review
      • Conclusion
  • Resources
  • Beginner
  • Advanced
  • Recommended Extensions for Visual Studio Code
  • Troubleshooting
    • Troubleshooting
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Book Module Tutorial
  2. Backend

Create Model

PreviousBackendNextCreate Service

Last updated 4 years ago

Was this helpful?

The first step is to identify the actors in our application. In this case, we can consider a user and a book as our models. Great! We can now create our classes in the models folder (We will not create a user class since it is already created).

We will use mongoose as our ORM.

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, out of the box.

Mongoose. (n.d.). Retrieved from

In our case, the book has three attributes, where we define for each attribute its type and other validations.

const mongoose = require("mongoose");

const bookSchema = new mongoose.Schema({
  Title: {
    type: String,
    required: true,
    lowercase: true,
    min: 2,
    max: 255
  },
  Author: {
    type: String,
    required: true,
    lowercase: true,
    min: 2,
    max: 255
  },
  ISBN: {
    type: Number,
    unique: true,
    required: true,
    min: 1000000000,
    max: 9999999999999,
    validate: {
      validator: Number.isInteger,
      message: "{VALUE} is not an integer value"
    }
  },

});

module.exports = mongoose.model("Book", bookSchema);

Note that each book has a unique ISBN and an ISBN is a number that has either 10 or 13 digits.

https://mongoosejs.com/