CREATING A MODEL IN NODEJS

 

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:-

// import mongoose module
let mongoose = require("mongoose");

// Syntax to define a Schema in Nodejs
let Schema = new mongoose.Schema({
  key1: {
    type: Number,
  },
  key2: {
    type: String,
  },
});

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:-

//The model function takes 2 parameters
// 1st one is the name of the collection in MongoDB
// 2nd one is the Schema
let Model = mongoose.model("sampleModel", Schema)

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:

  1. type: specifies the datatype of the field (String, Number, Date, and so on).
  2. 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.
  3. required: indicates that the value for the specific field should be empty.
  4. 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.
// import mongoose module
let mongoose = require("mongoose");

// Defining a User Schema in Nodejs
let userSchema = new mongoose.Schema({
  name: {
    type: String,
    default: "Harsha Vardhan Garlapati",
  },
  emailId: {
    type: String,
    required: true,
    unique: true,
  },
  mobile: {
    type: Number,
  },
  dateOfBirth: {
    type: Date,
  },
});

// Defining a User Model in Nodejs
let userModel = mongoose.model("userModel", userSchema);

// exporting the module to use in other service files for DB Operations
module.exports = userModel;


** Data validation is critical in real-time scenarios to prevent irrelevant data from being kept in the application. This contributes to data integrity. **
Harsha Vardhan Garlapati

As a software engineer and technology enthusiast, I thrive on exploring the ever-evolving world of technology and leveraging it to create innovative solutions. With a passion for sharing knowledge and insights, I also delve into the world of blogging to inspire and educate others in the realm of software development. Beyond the realm of code, I find joy in exploring new destinations as a passionate traveler, embracing diverse cultures, and broadening my horizons. In my free time, I cherish moments spent with friends, valuing the connections and experiences that enrich my life. Combining my technical expertise, love for writing, adventurous spirit, and the importance of human connections, I aim to leave a positive impact on the world through my work, experiences, and interactions. Let’s embark on this exciting journey together, exploring the wonders of technology while cherishing the moments that truly matter.

Post a Comment

Previous Post Next Post