To create a new schema type in mongoose, first let's setup our server, to get this example
- Open your terminal, and choose specific path. After choosing the path write
npm init -y
. Give all the basic details about your project. - Install some basic packages like
cors
,express
,mongoose
bynpm i express mongoose cors
. - After it get install write
code .
. It'll open VSCode for you. - Write the below code for your to make your server run
- 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
save this code as userModel.js
after creating schema lets create a controller, to add the user
save this code as userController.js
now lets create a route on Server.js
file to call this api
change your code accordingly, now finally create our own schema type name Color
save this code as colorSchema.js
I'll explain the code after a while, lets make the necessary changes and give it a run...
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)