Create Model

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 https://mongoosejs.com/

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.

Last updated