CodeBlanks Logo Icon CodeBlanks

Schema

Learn model schemas with Mongoose Schema.

The data blueprint

In Mongoose you define the data shape by creating a blueprint. This blueprint specifies which fields exist, their types (String, Number, Date), and validation rules. This keeps documents consistent.

The blueprint is written as a JavaScript object. For example { name: String, age: Number } defines two fields. Mongoose automatically builds a data structure from this definition. You cannot create a model without a blueprint; so the blueprint is the foundation of Mongoose.

Field types

Each field in a blueprint takes a type. Common types: String (text), Number (number), Date (date), Boolean (logical), Buffer (binary). The type determines how Mongoose stores and validates the document.

A type can also take options: { type: String, required: true, default: "name" }. required: true means the field cannot be empty; default gives a fallback value. This enforces data integrity at the application layer.

Practice Log the connection state

Import the mongoose module. Log mongoose.connection.readyState. (If not connected it is 0.)

Starter code

index.js
// import the module

// log the connection state

Sample solution

index.js
const mongoose = require("mongoose");
console.log(mongoose.connection.readyState);

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the module name

Question
const mongoose = require("____")
Answer
const mongoose = require("mongoose")

Explanation: The Mongoose module loads as 'mongoose'.

2 What determines a field's type in a blueprint?

  • A file name
  • A JavaScript constructor (String, Number...) Correct answer
  • A network connection
  • A port number

Explanation: The type is given by JavaScript constructors like String, Number.

3 Match each piece to its role

Term Meaning
String Text
Number Number
Date Date
Boolean Logical

All lessons in Advanced