Open In App

What is SchemaType in Mongoose ?

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is an Object Data Modeling (ODM) library for MongoDB and it provides a rich set of schema types to define the structure and data types of the documents stored in a MongoDB collection. 

A schemaType is used to define the data type and validation rules for a specific field in a schema.

Syntax:

const mySchema = new mongoose.Schema({
    myField: {
        type: MySchemaType,
        required: Boolean,
        default: Any,
        unique: Boolean,
        min: Number,
        max: Number,
        enum: Array,
        validate: Function
    }
});

 

Parameters:

  • Type: This parameter is used to specify the data type of the field. For example, String, Number, Date, etc.
  • Required: This parameter is used to specify whether the field is required or not. If set to true, Mongoose will throw a validation error if the field is not present in the document.
  • Default: This parameter is used to set a default value for the field. If no value is provided for the field, Mongoose will use the default value.
  • Unique: This parameter is used to specify whether the field value should be unique across all documents in the collection. If set to true, Mongoose will throw a validation error if a document with the same value for the field already exists.
  • Min/Max: These parameters are used to set minimum and maximum values for numeric fields such as Number and Date. Mongoose will throw a validation error if the value of the field is outside the specified range.
  • Enum: This parameter is used to specify a list of allowed values for the field. Mongoose will throw a validation error if the value of the field is not one of the allowed values.
  • Validate: This parameter is used to specify a custom validation function for the field. The function should take the value of the field as its parameter and return true if the value is valid, or false otherwise. Mongoose will call this function during validation.

Installation of mongoose module:

Step 1: You can install this package by using this command.

npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Step 3: After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.

node index.js

Project Structure: The project structure will look like this:

 

Example 1: In this example, we define a Mongoose schema for a “book” document with fields for the book’s title, author, page count, published date, availability, and genres. We set different parameters for each field such as required, min, default, enum, etc.

Then we create a Mongoose model using the schema and use it to create a new document object book with values for each field. We then call the save() method to save the document to the database.

Index.js

Javascript




const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => console.log("Connected to MongoDB"))
    .catch((err) => 
       console.error("Error connecting to MongoDB:", err));
  
// Define a Mongoose schema
const bookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    author: {
        type: String,
        required: true,
    },
    pageCount: {
        type: Number,
        min: 1,
        required: true,
    },
    publishedDate: {
        type: Date,
        default: Date.now,
    },
    isAvailable: {
        type: Boolean,
        default: true,
    },
    genres: {
        type: [String],
        enum: [
            "Fiction",
            "Non-Fiction",
            "Biography",
            "History",
            "Science Fiction",
            "Comedy",
        ],
    },
});
  
// Create a Mongoose model using the schema
const Book = mongoose.model("Book", bookSchema);
  
// Create a new document using the model
const book = new Book({
    title: "The Hitchhiker's Guide to the Galaxy",
    author: "Douglas Adams",
    pageCount: 215,
    isAvailable: false,
    genres: ["Science Fiction", "Comedy"],
});
  
// Save the document to the database
book.save(function (err, savedBook) {
    if (err) {
        console.log("Error saving book:", err);
    } else {
        console.log("Book saved successfully:", savedBook);
    }
});


Run the index.js file using below command:

node index.js

Output:

 

Example 2: In this example, we’re connecting to a MongoDB database and defining a Mongoose schema for a “person” document. The schema includes fields for first name, last name, age, and email.

Then we create a Mongoose model using the schema and create a new document object person with values for each field. Finally, we call the save() method to save the document to the database.

Index.js

Javascript




const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => console.log("Connected to MongoDB"))
    .catch((err) => 
       console.error("Error connecting to MongoDB:", err));
  
// Define a Mongoose schema
const personSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    age: Number,
    email: String,
});
  
// Create a Mongoose model using the schema
const Person = mongoose.model("Person", personSchema);
  
// Create a new document using the model
const person = new Person({
    firstName: "John",
    lastName: "Doe",
    age: 30,
    email: "john.doe@example.com",
});
  
// Save the document to the database
person.save(function (err, savedPerson) {
    if (err) {
        console.log("Error saving person:", err);
    } else {
        console.log("Person saved successfully:", savedPerson);
    }
});


Run the index.js file using the below command:

node index.js

Output:

 

Reference:  https://mongoosejs.com/docs/schematypes.html



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads