In this section, we will explore how to use MongoDB with Mongoose in a Node.js application. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward, schema-based solution to model your application data.

Table of Contents

Introduction to MongoDB and Mongoose

What is MongoDB?

  • MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It is designed for scalability and high performance.
  • Key Features:
    • Document-oriented storage
    • Indexing
    • Replication
    • Load balancing
    • Aggregation

What is Mongoose?

  • Mongoose is an ODM library for MongoDB and Node.js. It provides a schema-based solution to model application data.
  • Key Features:
    • Schema definitions
    • Middleware (pre and post hooks)
    • Validation
    • Type casting
    • Query building

Setting Up MongoDB

  1. Install MongoDB:

  2. Start MongoDB:

    • Run the following command to start the MongoDB server:
      mongod
      

Installing Mongoose

To use Mongoose in your Node.js application, you need to install it via npm.

npm install mongoose

Connecting to MongoDB

Create a new file app.js and add the following code to connect to MongoDB using Mongoose:

const mongoose = require('mongoose');

// Replace 'your_database_url' with your actual MongoDB connection string
const dbURL = 'mongodb://localhost:27017/mydatabase';

mongoose.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected...'))
  .catch(err => console.log(err));

Explanation:

  • mongoose.connect(): Connects to the MongoDB server.
  • useNewUrlParser and useUnifiedTopology: Options to handle deprecation warnings.

Defining Schemas and Models

Schema Definition

A schema defines the structure of the documents within a collection.

const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  age: {
    type: Number,
    min: 0
  }
});

Model Creation

A model is a compiled version of the schema, which provides an interface to interact with the database.

const User = mongoose.model('User', userSchema);

CRUD Operations

Create

const newUser = new User({
  name: 'John Doe',
  email: '[email protected]',
  age: 30
});

newUser.save()
  .then(user => console.log(user))
  .catch(err => console.log(err));

Read

User.find()
  .then(users => console.log(users))
  .catch(err => console.log(err));

Update

User.updateOne({ email: '[email protected]' }, { age: 31 })
  .then(result => console.log(result))
  .catch(err => console.log(err));

Delete

User.deleteOne({ email: '[email protected]' })
  .then(result => console.log(result))
  .catch(err => console.log(err));

Practical Exercises

Exercise 1: Create a New User

  1. Define a schema for a Product with fields: name, price, and category.
  2. Create a new product and save it to the database.

Solution:

const productSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  category: {
    type: String,
    required: true
  }
});

const Product = mongoose.model('Product', productSchema);

const newProduct = new Product({
  name: 'Laptop',
  price: 999.99,
  category: 'Electronics'
});

newProduct.save()
  .then(product => console.log(product))
  .catch(err => console.log(err));

Exercise 2: Find All Users

  1. Write a query to find all users in the User collection.

Solution:

User.find()
  .then(users => console.log(users))
  .catch(err => console.log(err));

Summary

In this section, we covered:

  • The basics of MongoDB and Mongoose.
  • How to set up MongoDB and install Mongoose.
  • Connecting to MongoDB using Mongoose.
  • Defining schemas and models.
  • Performing CRUD operations.

By now, you should have a good understanding of how to use MongoDB with Mongoose in a Node.js application. In the next section, we will explore using SQL databases with Sequelize.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved