To get started with Nodejs Model, we must first understand Nodejs Schema.
What is a Schema??
A document's structure is defined by its schema. It defines the attributes of a document using an object that contains the data in key-value pairs. This key property refers to the name of a property in a Mongo collection. While defining a document in a schema, we can describe the data types of the keys, define primary keys, and add some built-in and custom validations.
To create a schema, we must first
install the Mongoose library in the workspace. This may be accomplished with
the command npm i mongoose.
The syntax for creating a Schema:-
What is a Model?
A model provides an entity that facilitates interaction with the Mongo Collection. It provides an interface for performing database operations on the Mongo collections, such as create, delete, update, and retrieving actions, in order to obtain the documents. It is beneficial to query the documents in order to obtain the results. It serves as a wrapper for the Mongo schema.
The syntax for creating a model:-
Real-Time Example of a model:-
Referring to the link to my previous blog on Nodejs Application Folder Structure, let us build a userModel in the models folder, as seen below:-
Explanation of the userModel code below:-
- 2nd line à imported mongoose library
- 5th line à defined a userSchema with the necessary user data.
We have the following in the userSchema:
- type: specifies the datatype of the field (String, Number, Date, and so on).
- default: if no value is provided for this field, the default value is saved in the document in the mongo collection. By default, no validation is given to this field.
- required: indicates that the value for the specific field should be empty.
- unique: this indicates that the specific field is a primary key of the collection and will not tolerate duplicate values when adding / editing a document in a mongo collection.
- 24th line à defined the userModel, which aids with database operations.
- 27th line à exporting this userModel so that it can be utilized elsewhere in the application development.