CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that can be performed on data in a database. In this section, we will explore how to implement CRUD operations using Node.js with both MongoDB (using Mongoose) and SQL databases (using Sequelize).
- CRUD Operations with MongoDB and Mongoose
Setting Up Mongoose
First, ensure you have Mongoose installed in your Node.js project:
Connecting to MongoDB
Create a file named db.js to handle the database connection:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
module.exports = db;Defining a Schema and Model
Create a file named models/User.js:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
});
const User = mongoose.model('User', userSchema);
module.exports = User;Create Operation
To create a new user:
const User = require('./models/User');
// Create a new user
const createUser = async () => {
const user = new User({
name: 'John Doe',
email: '[email protected]',
age: 30,
});
try {
const savedUser = await user.save();
console.log('User created:', savedUser);
} catch (error) {
console.error('Error creating user:', error);
}
};
createUser();Read Operation
To read users from the database:
const User = require('./models/User');
// Read all users
const readUsers = async () => {
try {
const users = await User.find();
console.log('Users:', users);
} catch (error) {
console.error('Error reading users:', error);
}
};
readUsers();Update Operation
To update a user:
const User = require('./models/User');
// Update a user by ID
const updateUser = async (userId) => {
try {
const updatedUser = await User.findByIdAndUpdate(
userId,
{ age: 35 },
{ new: true }
);
console.log('User updated:', updatedUser);
} catch (error) {
console.error('Error updating user:', error);
}
};
updateUser('60c72b2f9b1d4c1f8c8b4567');Delete Operation
To delete a user:
const User = require('./models/User');
// Delete a user by ID
const deleteUser = async (userId) => {
try {
await User.findByIdAndDelete(userId);
console.log('User deleted');
} catch (error) {
console.error('Error deleting user:', error);
}
};
deleteUser('60c72b2f9b1d4c1f8c8b4567');
- CRUD Operations with SQL Databases and Sequelize
Setting Up Sequelize
First, ensure you have Sequelize and a SQL database driver (e.g., pg for PostgreSQL) installed:
Connecting to the Database
Create a file named db.js to handle the database connection:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'postgres',
});
module.exports = sequelize;Defining a Model
Create a file named models/User.js:
const { DataTypes } = require('sequelize');
const sequelize = require('../db');
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
age: {
type: DataTypes.INTEGER,
},
});
module.exports = User;Create Operation
To create a new user:
const User = require('./models/User');
// Create a new user
const createUser = async () => {
try {
const user = await User.create({
name: 'Jane Doe',
email: '[email protected]',
age: 28,
});
console.log('User created:', user);
} catch (error) {
console.error('Error creating user:', error);
}
};
createUser();Read Operation
To read users from the database:
const User = require('./models/User');
// Read all users
const readUsers = async () => {
try {
const users = await User.findAll();
console.log('Users:', users);
} catch (error) {
console.error('Error reading users:', error);
}
};
readUsers();Update Operation
To update a user:
const User = require('./models/User');
// Update a user by ID
const updateUser = async (userId) => {
try {
const user = await User.findByPk(userId);
if (user) {
user.age = 32;
await user.save();
console.log('User updated:', user);
} else {
console.log('User not found');
}
} catch (error) {
console.error('Error updating user:', error);
}
};
updateUser(1);Delete Operation
To delete a user:
const User = require('./models/User');
// Delete a user by ID
const deleteUser = async (userId) => {
try {
const user = await User.findByPk(userId);
if (user) {
await user.destroy();
console.log('User deleted');
} else {
console.log('User not found');
}
} catch (error) {
console.error('Error deleting user:', error);
}
};
deleteUser(1);Summary
In this section, we covered how to perform CRUD operations using Node.js with both MongoDB (using Mongoose) and SQL databases (using Sequelize). We learned how to:
- Set up and connect to MongoDB and SQL databases.
- Define schemas and models.
- Implement Create, Read, Update, and Delete operations.
These fundamental operations are essential for any application that interacts with a database. In the next module, we will delve into authentication and authorization, which are crucial for securing your application.
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
