top of page
Writer's picturePushp Raj

Understanding Mongoose Schemas and Models



A Mongoose is a must-have tool for building robust and scalable apps with MongoDB and Node.js. Mongoose is an Object-Document Mapping (ODM) module that defines schemas and models to give a simple and intuitive way to communicate with MongoDB.


In this article, we will look at the essential ideas of Mongoose schemas and models and how they may help you develop efficient and organized data models for your applications. This article will give you a solid foundation whether you are a newbie just getting started with MongoDB and Mongoose or an experienced developer wishing to go deeper into advanced Mongoose features.


First, we will define schemas and models and how they integrate within the Mongoose architecture. A Mongoose schema is a design template for specifying your MongoDB records' structure, data types, and validation criteria. It lets you define the fields, their kinds, default values, and other options. Schemas provide a clear framework for your data and aid with document consistency.


Following that, we'll look at Mongoose models, structures based on schemas. Models provide a user interface for interacting with MongoDB collections and performing database operations such as querying, inserting, updating, and removing documents. They serve as a link between your application and the underlying MongoDB database, making data manipulation easier.


We will look at the many capabilities and functionalities that Mongoose schemas and models provide. Defining associations between collections using references or embedded documents, adding validation and custom validation logic, constructing indexes for efficient querying, handling middleware functions, and much more are all part of this. Understanding these concepts will enable you to create robust and flexible data models that meet the needs of your application.


We will present examples and code snippets to demonstrate the principles mentioned throughout this tutorial. By the end of this course, you will have a firm understanding of Mongoose schemas and models, allowing you to create scalable and maintainable MongoDB data models for your Node.js applications.


So, let us begin this adventure of understanding Mongoose schemas and models to utilize MongoDB in your Node.js projects fully.


Pre-requisites


Although this is a beginner-friendly course for learning Mongoose schema and models, it is recommended that you have the following for a better understanding:


  • It would be beneficial to have Node.js installed on the system. Refer to the installation procedures for Windows and Linux.

  • It is best to install Mongoose and connect it to the MongoDB database.


A Mongoose model is a Mongoose schema wrapper. A Mongoose schema defines the document's properties, default values, data types, validators, and so on. A Mongoose model, on the other hand, provides an interface for the database to create, query, update, and remove records, among other things.


Creating a Mongoose schema and models is divided into three steps. Let's look at all of them:


Referencing Mongoose


This is the same as when we connected our database, implying that declaring Schema and Model does not necessitate an explicit connection to the database.


let mongoose = require('mongoose');

const { Schema } = mongoose;


Defining Schema/ Schema Definition


We design a schema to determine the object's properties, such as default values, data types, etc.

const blogSchema = new Schema({

// String is shorthand for {type: String}

title: String,

date: { type: Date, default: Date.now },

body: String,

});


Now, blogSchema defines a few essential blog attributes here. We've defined a String SchemaType property title and body and a Date SchemaType property date, with the default value set to Date.now, which returns the current date.


Mongoose currently supports ten SchemaTypes. They are as follows:


● Array

● Boolean

● Buffer

● Date

● Mixed (A generic/flexible data type)

● Number

● ObjectId

● String

● Decimal 128

● Map


Creating and Exporting the Model


To use the defined schema, we must turn blogSchema into a Model we can operate with.


We will use the Mongoose.model(<CollectionName>, <CollectionSchema>) function to accomplish this. This function accepts two parameters, CollectionName (the name of the collection) and CollectionSchema (the collection's schema) produces a mongoose Model object.


let Blog = mongoose.model('Blogs', blogSchema); //creating a Model

module.exports = Blog //Exporting the created module.


Now that we've successfully constructed a Mongoose schema and models, we can use this blog model to efficiently conduct database operations such as create, read, update, delete, etc.


Mongoose Schema and Models are used for Basic Operations


Mongoose schema and models conduct fundamental MongoDB Collection actions such as create, query, update and delete.


Note: We can do all of these procedures in multiple ways, but we will only go into detail about them here if they are outside the scope of this article.


Create Records: Make a blog model instance and save it to the MongoDB database.


// Creating newBlog object using blog Model


var newBlog = new Blog({

title: "New Blog to create record",

body: "This is a sample blog created for CipherSchools."

})



// Saving newBlog to database

newBlog.save()

.then(doc => {

console.log(doc)

})


.catch(err => {

console.error(err)

})

Upon successful submission, a document is produced.

{

_id: 5a78fe3e2f44ba8f85a2409a,

title: "New Blog to create record",

body: "This is a sample blog created for coding ninja tutorial,"

date: 08-12-2021 13:14

__v: 0

}


We can see in the returned document that the __id attribute is auto-generated by Mongo and serves as the collection's primary key. The blog schema defines three fields with values: title, body, and date. __v is the version fundamental property for each document when Mongoose first produces it.


Fetch Record: Now, let's try to retrieve the record we previously saved to the database. We'll use the find() method to find the document and supply the title as a search item.


// Fetching records from the database


Blog.find({

// search query

title: 'New Blog to create record'

})

.then(doc => {

console.log(doc)

})

.catch(err => {

console.error(err)

})

The result returned is the same as when the document was created.

{

_id: 5a78fe3e2f44ba8f85a2409a,

title: "New Blog to create record",

body: "This is a sample blog created for coding ninja tutorial,"

date: 08-12-2021 13:14

__v: 0

}


Update Record: We will now update the record we previously saved to the database. The findOneAndUpdate() method will be used to update the document.


/ Fetching records from the database


Blog.findOneAndUpdate(

{

// Search query

title: "New Blog to create record",

},

{

// Field: values to update

title: "Blog updated in the record",

},

{

// To return the updated doc

new: true,

}

)

.then((doc) => {

// Updated doc returned

console.log(doc);

})

.catch((err) => {

// Error displayed

console.error(err);

});

The console will receive the modified document.

{

_id: 5a78fe3e2f44ba8f85a2409a,

title: "Blog updated in the record",

body: "This is a sample blog created for coding ninja tutorial,"

date: 08-12-2021 13:14

__v: 0

}


Delete Record: Let's look at how to delete the record we previously saved to the database. Using the findOneAndRemove() method, we will delete the record.


// Fetching records from the database


Blog.findOneAndRemove({

// Search query

title: "Blog updated in the record"

})

.then((doc) => {

console.log(doc)

})

.catch(err => {

console.error(err)

})

The code above will delete the discovered record.

{

_id: 5a78fe3e2f44ba8f85a2409a,

title: "Blog updated in the record",

body: "This is a sample blog created for coding ninja tutorial,"

date: 08-12-2021 13:14

__v: 0

}


Creating a model with Mongoose Schemas


To see how Mongoose is used to generate a model in databases using a schema, we will need the following software. We'll need a coding editor like VS coding, Nodejs and a database reader like Robo 3T, now called Studio 3T.


Step 1: In VS Code, create a new folder and a new file, app.js. Now, launch the terminal and enter the following command. This command will launch a node project and generate a package.json file with information about our project and its dependencies. It also contains the script commands that we define.


npm init -y


We need to add a script command to our node project now that we've created it. Open the package.json file, add a new key, start, and set its value to "node app.js" beneath the script's key.


Step 2: When a Nodejs-built web application is hosted, the hosting service or other individuals reading your code use the command listed below to execute it; otherwise, they must look for the name of your main file and then write a command specifically for it. The start command generalizes the idea of launching a Nodejs application.


npm start


Note: Because we haven't typed any code in our JavaScript file, the above command will do nothing for now.


Step 3: The third step is importing the library and connecting it to the database. We can't immediately start writing code to build up and use a MongoDB database using the Mongoose module.


The essential libraries must be installed from the NPM repository, a cloud repository of third-party packages for Nodejs applications. To install the MongoDB and Mongoose libraries, enter the following instructions into the console.


npm install mongodb mongoose


Now enter the code below into the app.js file to import the Mongoose library and connect to a MongoDB database using its connect method. If no such database exists, one will be established.


The URL indicated in the code below is for local DB, with our database name at the end. A URL can also be added to a cloud MongoDB database.


We don't import or utilize the MongoDB library because it was only required for the Mongoose library to function in the background. Remember that Mongoose only works with MongoDB databases.


file: app.js

JavaScript Code:


const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/magesDB");


Step 4: Choosing a Model Blueprint. We're building a database to store information about magicians hidden all around the planet. The mage will have a name, a power type, gold, health, and mana abilities.


As a result, these are the fields that each mage will have here. In MongoDB, a collection is analogous to a table, and a document is equivalent to a table row containing all data representing a single entity.


We utilize the Mongoose constant to access all of the Mongoose library's methods. We invoke the Schema method and provide it with a JavaScript object with the abovementioned fields. Their values represent the data types that will be stored.


We will not provide any solid facts because this is only a plan. We may also pass an object to a key, which will specify additional field properties. The only other attribute we require is that the name and power type keys cannot be empty. As a result, we set the necessary key to true. As illustrated below, all of this must be assigned to a constant.


We utilize the Mongoose.model function to make this blueprint, or schema, a reality. The first argument is the collection's name, and the second is the schema. Maintain the string's case precisely as shown. Mongoose will change it to the small case and singular automatically. Make a constant out of it. This constant is now a class from which we can generate several instances.


file: app.js

JavaScript Code:


const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new Mongoose.Schema({

name: {

type: String,

require: true

},

power_type: {

type: String,

require: true

},

mana_power: Number,

health: Number,

gold: Number

})

const Mage = new Mongoose.model("Mage", mageSchema)


Step 5: Make and save a model. Now that we have a class from which we can generate objects that will act as documents for the collection that the class represents, we use the new keyword and the save() function to create and save it.


Create an object from the Mage class using the new keyword, which invokes a constructor method, as you would in a traditional OOP approach. Then, on this object, execute the save() method. This will result in creating a document in the mage's collection. Now execute the code using the command below.


file: app.js

JavaScript Code:


const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new Mongoose.Schema({

name: {

type: String,

require: true

},

power_type: {

type: String,

require: true

},

mana_power: Number,

health: Number,

gold: Number

})

const Mage = new Mongoose.model("Mage", mageSchema)

const mage_1 = new Mage({

name: "Anurag",

power_type: 'Element',

mana_power: 40,

health: 10,

gold: 5000

});

mage_1.save();


You may view the stored model and document by launching the Studio 3T desktop application, choosing Connect, navigating through the hierarchy, and double-clicking on the mode collection name.

Now, double-click on the name of the collection. It has been automatically assigned an _id field.


You can construct as many objects from the Mage class as you want and then call the save() function on each of them to create a document in the Mages collection for each of them.

File: app.js


JavaScript Code:


const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new Mongoose.Schema({

name: {

type: String,

require: true

},

power_type: {

type: String,

require: true

},

mana_power: Number,

health: Number,

gold: Number

})

const Mage = new Mongoose.model("Mage", mageSchema)

const mage_1 = new Mage({

name: "Anurag",

power_type: 'Element',

mana_power: 40,

health: 10,

gold: 5000

});


mage_1.save();

const mage_2 = new Mage({

name: "Steve",

power_type: 'Physical',

mana_power: "500",

health: "5000",

gold: "50"

})

mage_2.save();




Conclusion


Finally, while working with MongoDB with Node.js, understanding Mongoose schemas and models is critical for creating efficient and organized data structures. Developers can use Mongoose to simplify the process of dealing with MongoDB, assuring their applications' scalability, flexibility, and maintainability.


Throughout this guide, we looked at the fundamental ideas of Mongoose schemas and models. Schemas, we discovered, serve as blueprints for defining the structure, data types, and validation criteria of MongoDB documents. They give the data uniformity and structure, making it easier to deal with.


Models, on the other hand, act as conduits between the application and the database. They allow developers to conduct CRUD operations, query data, and build collection relationships. Models make database interactions easier by encapsulating typical database operations in simple methods.


We also looked at advanced Mongoose capabilities, including handling collection relationships, implementing validation logic, building indexes for optimized queries, and utilizing middleware functions. These capabilities enable developers to create robust and adaptable data models tailored to their application's demands.


You now have a solid basis for designing scalable and maintainable MongoDB data models for your Node.js apps if you follow the examples and code snippets in this guide. Understanding Mongoose schemas and models will improve your development process and contribute to your applications' overall performance and efficiency.


Remember to investigate the official documentation, community resources, and other lessons as you continue your Mongoose adventure to enhance your knowledge and find new techniques. Mongoose provides many capabilities and options to improve your MongoDB development experience dramatically.


With this newfound knowledge, you can harness the power of Mongoose schemas and models to construct robust, scalable, and efficient MongoDB data models for your Node.js projects. Have fun coding!


Interesting F.A.Q


What is the typical MERN stack developer pay in India?

According to Glassdoor, the average compensation for a MERN Stack Developer in India is $4,59,200 per year. In India, the average additional cash compensation for a MERN Stack Developer is 39,200, with a range of 7,500 - 98,306. Estimated salaries are based on 174 MERN Stack Developer salary reports given anonymously to Glassdoor by MERN Stack Developer workers in India.

What abilities are required for a MERN stack developer?


University of Central Florida state's a career as a full stack developer necessitates a specific set of talents. Full stack developers, like mechanics who determine that they haven't completely mended a car until they've rehabbed its cumbersome engine and reupholstered the seats, must be both driven and diverse in their professional abilities, incorporating the following skillsets:

  • JavaScript

  • MongoDB

  • Express

  • React

  • Node. js





11 views

Related Posts

See All

Comments


Subscribe to Our Newsletter

Thanks for submitting!

bottom of page