Open In App

Mongoose Tutorial

Last Updated : 14 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. Follow these articles to install depending on your system:

Let us now take a look at our first code example.

JavaScript
//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));

It will insert a document with the provided details into the User collection in MongoDB.

In this 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.
Mongoose Tutorial -GeeksforGeeks

Why Learn Mongoose?

  • Simplifies MongoDB operations with built-in schema validation.
  • Reduces boilerplate code for database interactions.
  • Supports middleware for pre/post operations.
  • Well-suited for Node.js applications.

Mongoose Tutorial Prerequisites: JavaScript, Node.js, and MongoDB basics

Mongoose Basics

Mongoose Functions

Mongoose Projects

MongoDB Introduction

MongoDB Installation

Basics of MongoDB

MongoDB Methods

MongoDB Operators

Comparison Operators

Logical Operators

Arithmetic Operators

Field Update Operators

Array Expression Operators

Array Update Operators

String Expression Operators

Working with Documents and Collections

Indexing in MongoDB

MongoDB Advance

MongoDB For Interview

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

FeatureMongooseMongoDB Native Driver
Abstraction LevelHigh (uses models and schemas)Low (raw queries)
Data ValidationBuilt-inManual
Middleware SupportYesNo
Learning CurveModerateSteeper
Use CaseComplex ApplicationsLightweight Apps or Scripts

More on Mongoose:


Similar Reads