MongoDb Schema
How to create a schema file & use it in a model explained in MongoDB - simplest Schema, also explained useful settings after schema, how to connect (bind) collections etc.
We should think about all possibly requires that help to add to DB good enough data.
-
Name
-
f.e. for name of goods, users possibly enough will be
See the Pen 20-A -- NAME -- field in Schema by Andrii (@imitator) on CodePen.
Usually for frontend person enough the answer message that created by the server (like "product validation failed: name: Path `name` is required."), but sometime we should change it by
See the Pen 20 - B __ Schema, change the answer message by Andrii (@imitator) on CodePen.
In this more specification case for "required" filed the answer will be "product validation failed: name: Product name should be provided"
Also we may add the specific answer for other fields, f.e. for "minlength"
See the Pen 20 - C __ Schema, specific for minlength field message by Andrii (@imitator) on CodePen.
-
f.e. for name of goods, users possibly enough will be
-
Price
For price
See the Pen 20 - D __ schema PRICE filed by Andrii (@imitator) on CodePen.
-
Article, category
Sometime we need to create unique filed, that will not be repeated, f.e. categories, articles e.t.c., but in documentation of mongoose reported that it doesn't work correctly, BE CAREFUL with itSee the Pen 20 - E __ schema UNIQUE field by Andrii (@imitator) on CodePen.
Teacher explained it in webinar, from 1:46:15 - 1:48:30 -
Active
Example, when f.e. product isn't available for this moment, so we should update "active" filed for "false". In this example every good by default will be active: true, means when we add new product the filed "active" automatically will be addedSee the Pen 20 - F __ schema ACTIVE field by Andrii (@imitator) on CodePen.
-
Status
Example when we have only 3 product statusesSee the Pen 20 - G __ schema STATUS filed by Andrii (@imitator) on CodePen.
-
Match (example for e-mail)
Sometime, according to requirements we should make regular expression for specific fields
See the Pen 20 - H _ schema MATCH - regular expression for some field by Andrii (@imitator) on CodePen.
- Custom Validators are used for more specific filed requirements
- Remember about reusing filed validation in different schemas, f.e. e-mail filed by Subdocuments
-
At the end of a Schema added object { versionKey: false,
timestamps: true },
-
timestamps
"createdAt": "2023-04-24T08:11:22.280Z","updatedAt": "2023-04-24T08:11:22.280Z"
-
timestamps
- How to use schema in model explained in Simplest schema, point 2