MongoDB is a NoSQL database that stores data in flexible, JSON-like documents, making it an excellent choice for applications that require high performance and scalability. In this module, we will introduce MongoDB, show how to integrate it with Node.js using Mongoose, and explore basic CRUD (Create, Read, Update, Delete) operations.
Table of Contents
- Introduction to MongoDB
- Setting Up MongoDB in Node.js
- Introduction to Mongoose
- Defining Schemas and Models
- Basic CRUD Operations with Mongoose
- Working with Relationships in MongoDB
- Validations and Middleware in Mongoose
- Conclusion
1. Introduction to MongoDB
MongoDB is an open-source, document-oriented NoSQL database designed for scalability and flexibility. Unlike traditional relational databases, MongoDB stores data in collections of documents rather than in tables with rows and columns. Each document is a JSON-like object, which allows for nested structures and dynamic schemas.
MongoDB is ideal for use cases where the structure of data may change over time or when dealing with large volumes of unstructured data. Some key features of MongoDB include:
- Flexible Schema: Each document in a collection can have a different structure.
- Scalability: MongoDB is designed for horizontal scaling, allowing you to handle high traffic and large datasets.
- High Availability: MongoDB supports replication, ensuring your data is available even in the event of server failures.
In the context of Node.js, MongoDB is often used as a database for storing application data, and the Mongoose library is used to interact with it more easily.
2. Setting Up MongoDB in Node.js
Before we can begin working with MongoDB, we need to install and set up the MongoDB server. You can install MongoDB locally or use a cloud-based service like MongoDB Atlas for easy setup.
Step 1: Install MongoDB Locally (Optional)
To install MongoDB locally, visit the MongoDB download page and follow the installation instructions for your operating system.
Once installed, you can start the MongoDB server by running the following command:
mongod
This will start the MongoDB server on your local machine, typically accessible at mongodb://localhost:27017
.
Step 2: Installing Mongoose
Mongoose is an Object Data Modeling (ODM) library that provides a higher-level abstraction over MongoDB’s native driver. It makes working with MongoDB easier by providing features like schemas, validations, and middleware.
To install Mongoose, run the following command in your project directory:
npm install mongoose --save
3. Introduction to Mongoose
Mongoose provides a powerful way to interact with MongoDB in Node.js by defining models, schemas, and performing CRUD operations. A Schema is a blueprint for the structure of documents within a MongoDB collection, while a Model is a compiled version of the schema that allows for database operations.
In Mongoose, models are used to create, read, update, and delete data from the database. Here’s a basic example of how Mongoose integrates with MongoDB:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
age: Number,
email: String,
});
const User = mongoose.model('User', userSchema);
const newUser = new User({ name: 'John Doe', age: 30, email: '[email protected]' });
newUser.save()
.then(() => console.log('User saved'))
.catch(err => console.log(err));
4. Defining Schemas and Models
Schemas define the structure of documents in a collection. Each field in the schema corresponds to a field in a document. You can also define field types, default values, required fields, and more.
Example: Defining a Schema
const userSchema = new Schema({
name: { type: String, required: true },
age: { type: Number, min: 18 },
email: { type: String, unique: true },
});
In this example:
- The
name
field is required. - The
age
field must be a number and greater than or equal to 18. - The
email
field must be unique.
Creating a Model
Once a schema is defined, you can create a model based on it. The model is used to interact with the MongoDB collection.
const User = mongoose.model('User', userSchema);
5. Basic CRUD Operations with Mongoose
Mongoose provides an easy-to-use API for performing CRUD operations. Let’s go through each one:
Create:
To create a new document, instantiate a model with the data and call save()
:
const newUser = new User({ name: 'Alice', age: 25, email: '[email protected]' });
newUser.save()
.then(() => console.log('User created'))
.catch(err => console.log(err));
Read:
You can retrieve documents using methods like find()
, findOne()
, or findById()
:
User.find({ age: { $gte: 18 } }) // Find all users age >= 18
.then(users => console.log(users))
.catch(err => console.log(err));
User.findById('some-user-id')
.then(user => console.log(user))
.catch(err => console.log(err));
Update:
To update an existing document, you can use updateOne()
, updateMany()
, or findByIdAndUpdate()
:
User.findByIdAndUpdate('some-user-id', { age: 26 })
.then(() => console.log('User updated'))
.catch(err => console.log(err));
Delete:
To delete a document, use deleteOne()
, deleteMany()
, or findByIdAndDelete()
:
User.findByIdAndDelete('some-user-id')
.then(() => console.log('User deleted'))
.catch(err => console.log(err));
6. Working with Relationships in MongoDB
MongoDB is a NoSQL database, meaning it does not use foreign keys like relational databases. However, you can still represent relationships between data by embedding documents or using references.
Embedding Documents (One-to-Many Relationship)
You can store related data within the same document:
const postSchema = new Schema({
title: String,
content: String,
comments: [{ text: String, date: Date }],
});
const Post = mongoose.model('Post', postSchema);
Using References (Many-to-One Relationship)
You can use references to associate documents in different collections:
const postSchema = new Schema({
title: String,
content: String,
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
});
7. Validations and Middleware in Mongoose
Mongoose allows you to define validations for your schema fields, ensuring data integrity. For example:
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
});
Mongoose also provides middleware functions (also known as hooks) to run code before or after certain actions, such as saving or deleting a document.
Example: Pre-save Hook
userSchema.pre('save', function(next) {
if (!this.email.includes('@')) {
return next(new Error('Invalid email address'));
}
next();
});
8. Conclusion
In this module, we learned how to integrate MongoDB with Node.js using the Mongoose ODM library. We explored how to define schemas, models, and perform basic CRUD operations. MongoDB and Mongoose provide a powerful solution for handling data in a Node.js environment, enabling you to build scalable and flexible applications.
In the next module, we will delve deeper into advanced topics like Authentication with Passport.js and JWT (JSON Web Tokens) for building secure applications.