Connecting MongoDB
Database with Node
Application
• Mongoose acts as an Object Data Modeling (ODM) library, making it
easier to structure and interact with MongoDB from Node.js.
• Prerequisites:
• Node js
• MongoDB
Steps to Connect MongoDB Database with Node Application
1.Create a project folder using the following command.
mkdir mongodb-connection
cd mongodb-connection
2.Initialize the node project using the following command.
npm init –y
3.Install the required dependencies
npm i express mongodb mongoose
Sample example
// index.js
const express = require("express");
const app = express();
console.log("App listen at port 5000");
// To connect with your MongoDB database
const mongoose = require("mongoose");
// Connecting to database
mongoose.connect(
"mongodb://localhost:27017/",
{
dbName: "yourDB-name",
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) =>
err ? console.log(err) : console.log(
"Connected to yourDB-name database")
);
To start the application run the following command.
nodemon index.js
Mongoose ODM
• Mongoose is a popular ODM (Object Data Modeling) library for
MongoDB and Node.js that simplifies database interactions by
providing a schema-based solution to model application data. It is
widely used to build scalable, structured, and efficient
database-driven applications.
• Built on MongoDB for seamless integration with Node.js applications.
• Provides schema-based modeling to define document structure.
• Includes built-in validation to ensure data consistency.
• Enables easy querying and data relationships with chain query
methods.
To Start with Mongoose, you need to install and import it into your
project.
• EXAMPLE
//import mongoose in the application
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define a schema
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String,
});
// Create a model
const User = mongoose.model('User', userSchema);
// Insert a document
const user = new User({
name: 'Mohit Kumar',
age: 25,
email: '[email protected]',
});
user.save()
.then(() => console.log('User saved'))
.catch((err) => console.error('Error:', err));
• In the above example
• Mongoose connects to a local MongoDB database
using mongoose.connect().
• A schema is defined (userSchema) to enforce the structure of
documents in the User collection.
• A model (User) is created based on the schema, acting as an interface
for database operations.
• A new User instance is created and saved to the database using the
.save() method.
• Advantages of Mongoose
• Schema Definition: Mongoose allows you to define structured schema
model for MongoDB collections, because of that you get a clear
understanding about the structure of model data.
• Data Validation: It can be used for data validation, which ensures that only
valid and properly formatted data is stored in the database, which helps to
manage data integrity.
• Middleware Support: Mongoose has the support of middleware which
helps in the execution of custom logic before or after database operations,
that offers flexibility in handling data interactions.
• Query Building: We don't have to write those complex queries which we
were writing in MongoDB because Mongoose simplifies the process by
providing a high-level API that makes it easier to interact with the database.
• Modeling Relationships and Population: You can define relationships
between different data models and it also supports population, due to this
you can work with related data without disturbing database normalization.
Mongoose vs MongoDB Native Driver
Feature Mongoose MongoDB Native Driver
Abstraction Level High (uses models and schemas) Low (raw queries)
Data Validation Built-in Manual
Middleware Support Yes No
Learning Curve Moderate Steeper
Use Case Complex Applications Lightweight Apps or Scripts
Schema design of Mongoose ODM
ODM stands for Original Design Manufacturer
Mongoose ODM provides robust data validation capabilities at the
schema level, ensuring data integrity before documents are saved to a
MongoDB database. This validation occurs in the application layer,
offering more flexibility and detailed error handling than database-level
constraints.
How Mongoose Validation Works:
Schema Definition: Validation rules are defined within the Mongoose
schema for each field.
Automatic Execution: Validation automatically runs as a pre('save')
hook when the save() method is called on a Mongoose document.
Error Handling: If any validation rule fails, Mongoose throws a
ValidationError, preventing the document from being saved and
providing details about the failed validation.
What Are Mongoose SchemaTypes?
In Mongoose, SchemaTypes define the types of data that a specific field
in a MongoDB collection can store. Each SchemaType corresponds to a
specific MongoDB data type, allowing us to enforce consistent
structure and validation rules for our documents.
Mongoose SchemaTypes support various data types, including strings,
numbers, dates, arrays, objects, booleans, and more. By using
SchemaTypes, Mongoose ensures that data is consistent and validates
according to the type specified.
Syntax:
const schema = new Schema({
name: { type: String },
age: { type: Number, default: 10 },
});
• The purpose of using Mongoose SchemaTypes is to structure and validate
data consistently. Here are some key reasons why SchemaTypes are
important in MongoDB and Mongoose:
• Data Validation: SchemaTypes enforce validation rules that ensure data
integrity before it is saved in the database.
• Type Safety: By defining specific types for each field, SchemaTypes help
prevent type mismatches and errors.
• Query Optimization: Mongoose and MongoDB optimize queries based on
the field types, improving performance when retrieving data.
• Default Values: SchemaTypes allow you to set default values for fields,
ensuring that they are always initialized when a document is created.
Example of Validation:
const productSchema = new Schema({
name: { type: String, required: true },
price: { type: Number, min: 0 },
category: { type: String, enum: ['Electronics', 'Clothing', 'Food'] }
});
const Product = mongoose.model('Product', productSchema);
• What is Mongoose Schema and Model?
• Before diving into creating a model, it's important to understand
the schema and model concepts in MongoDB:
• Schema: A MongoDB schema defines the structure of documents
within a collection. It specifies the fields, their types, validation rules,
default values, and other constraints.
• Model: A model is a wrapper around the schema that allows us to
interact with the MongoDB database (CRUD operations like create,
read, update, delete). It provides an interface for querying and
manipulating the data.
STEPS FOLLOW LINK IN GEEKS OF GEEKS
https://www.geeksforgeeks.org/mongodb/mongoose-schemas-creatin
g-a-model/
Benefits of Using Mongoose Schema and Model
1.Schema Validation: Mongoose automatically validates data based on the defined schema before saving it
to the database.
2.Ease of Use: Mongoose provides a simple interface to work with MongoDB, eliminating the need to write
complex queries manually.
3.Middleware Support: Mongoose supports middleware (pre and post hooks), allowing you to run custom
logic before or after database operations.
4.Query Building: Mongoose simplifies querying with its chainable query-building API.