Open In App

Mongoose Schematype

Mongoose is a MongoDB object modeling and handling for node.js environment.

Mongoose Schematype is a configuration for the Mongoose model. Before creating a model, we always need to create a Schema. The SchemaType specifies what type of object is required at the given path. If the object doesn’t match, it throws an error. The SchemaType is declared as follows:



const schema = new Schema({
    name: { type: String },
    age: { type: Number, default: 10 }, 
});

Data Types supported by SchemaType:

Properties of SchemaType



const studentSchema = new Schema({
    name: { type: String }, // String type

    // Has a default value of numerical type
    age: { type: Number, default: 8},

    // Containing Date of birth as Date object 
    dob: { type: Date }, 
    skills: [{ type: String }] ,// Array of strings
});

Example: In the following example, we will create a SchemaType for a Student that will contain the fields name, age, skills and date of birth. Then we will save it to MongoDB using mongoose. Node.js and NPM are used in this example, so it is required to be installed.

Step 1: Create a folder and initialize it:

npm init

Step 2: Install mongoose in the project.

npm i mongoose

The project structure is as follows:

 

Step 3: Create a file called index.js. Inside the index.js, connect to MongoDB. Here the MongoDB Compass is used. First, create the Schema, then the Model from Schema, and name it Student. Finally, create a document of the Student model and save it to the database using the save() function.

index.js
 

Step 4: Now run the code using the following command in the Terminal/Command Prompt to run the file.

node index.js

Output: The output for the code is as follows:

 

And the document in the MongoDB is as follows:

 

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

Article Tags :