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
-
Install MongoDB:
- Follow the instructions on the official MongoDB website to install MongoDB on your system.
-
Start MongoDB:
- Run the following command to start the MongoDB server:
mongod
- Run the following command to start the MongoDB server:
Installing Mongoose
To use Mongoose in your Node.js application, you need to install it via npm.
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.useNewUrlParseranduseUnifiedTopology: 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.
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
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
- Define a schema for a
Productwith fields:name,price, andcategory. - 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
- Write a query to find all users in the
Usercollection.
Solution:
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
- Introduction to NPM
- Installing and Using Packages
- Creating and Publishing Packages
- Semantic Versioning
Module 6: Express.js Framework
- Introduction to Express.js
- Setting Up an Express Application
- Middleware
- Routing in Express
- Error Handling
Module 7: Databases and ORMs
- Introduction to Databases
- Using MongoDB with Mongoose
- Using SQL Databases with Sequelize
- CRUD Operations
Module 8: Authentication and Authorization
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with Mocha and Chai
- Integration Testing
- Debugging Node.js Applications
Module 10: Advanced Topics
Module 11: Deployment and DevOps
- Environment Variables
- Using PM2 for Process Management
- Deploying to Heroku
- Continuous Integration and Deployment
