DEV Community

Abhishek Kumar
Abhishek Kumar

Posted on • Updated on

Create your own Schema Type in mongoose

To create a new schema type in mongoose, first let's setup our server, to get this example

  1. Open your terminal, and choose specific path. After choosing the path write npm init -y. Give all the basic details about your project.
  2. Install some basic packages like cors, express, mongoose by npm i express mongoose cors.
  3. After it get install write code .. It'll open VSCode for you.
  4. Write the below code for your to make your server run

Image description
save this code in Server.js

  1. This will make you a basic structure of server. After that run node Server.js.

Your server is now running, now to create the schema type of your own, you first need to make a schemaModel. Before creating schema model, lets discuss about what we are gonna make... (Do you thought any... if then please mention it in comments). For me I am thinking to make a Color schema type, which will automatically fill the Color to the new field being entered. Sounds good right?
So before creating our own Color schemaField let's create a small user schema

Image description
save this code as userModel.js

after creating schema lets create a controller, to add the user

Image description
save this code as userController.js

now lets create a route on Server.js file to call this api

Image description

change your code accordingly, now finally create our own schema type name Color

Image description
save this code as colorSchema.js

I'll explain the code after a while, lets make the necessary changes and give it a run...

Image description
make the changes accordingly in userModel.js

now when you'll hit the api, it will automatically create a color in your data.

Now come to the important part i.e being known what's happening in colorSchema.js file

so whenever we're extending schemaType form mongoose, the default function is triggered if no data is provided. In this case, it returns nothing. Then, the cast function is executed, where the val variable holds the current value. If val is present, it is returned; otherwise, a random color from the specified array is set.

Top comments (0)