Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Mongoose In Action - Defining the Schema

January 25th 2021   234

Mongoose In Action - Defining the Schema
Mongoose In Action - Defining the Schema
const todoSchema = new Schema(
  {
    description: {
      type: String,
      required: true,
    },
  },
);

So here we have created an instance of Schema and named it todoSchema. The Schema takes object as a parameter, so we had passed an object and inside that we have a key called description and its value is again an object in which we had specified we need a field description of type “String”, this type is in-built with mongoose you can refer more on official docs and also it is a required field so we had defined this with the key required and with a boolean value of true.

Lets add more field into the schema,

const todoSchema = new Schema(
  {
    description: {
      type: String,
      required: true,
    },
    completed: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

So similarly we had define a field called completed and it is of type Boolean and it hold a default value false.

And if you carefully looked at the structure we had passed a second parameter which is an object with a key timestamps so this second parameter is a configuration object in which we had only used an inbuilt feature of mongoose which adds to additional fields to every documents namely “createdAt” and “updatedAt”.

The following Schema Types are permitted:

  • Array
  • Boolean
  • Buffer
  • Date
  • Mixed (A generic / flexible data type)
  • Number
  • ObjectId
  • String