Schema in Mongoose

·

1 min read

The schema in Mongoose is used to allow you to define the fields stored in each document along with their validation requirements and default values.

they also define document instance methods, static Model methods, compound indexes, and document lifecycle hooks called middleware.

The permitted SchemaTypes are:

  • String

  • Number

  • Date

  • Buffer

  • Boolean

  • Mixed

  • ObjectId

  • Array

  • Decimal128

  • Map

  • UUID

Creating Schema

import mongoose from 'mongoose';
const { Schema } = mongoose;

const blogSchema = new Schema({
  title: String, // String is shorthand for {type: String}
  author: String,
  body: String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs: Number
  }
});

Creating schema model

To use our schema definition, we need to convert our blogSchema into a Model we can work with. To do so, we pass it to the mongoose.model(modelName, schema):

const Blog = mongoose.model('Blog', blogSchema);