Learn to integrate databases with Node.js applications using MongoDB, PostgreSQL, and popular ORMs.
Learn to integrate databases with Node.js applications using MongoDB, PostgreSQL, and popular ORMs.
Learn to work with MongoDB using Mongoose ODM for Node.js applications
Content by: Prakash Patel
Node.js Developer
MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js that provides a straightforward schema-based solution for modeling application data.
// Install dependencies
npm install mongoose
// Connect to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
// Define a Schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 0,
max: 120
},
createdAt: {
type: Date,
default: Date.now
}
});
// Create a Model
const User = mongoose.model('User', userSchema);
// Using the Model
const newUser = new User({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
newUser.save()
.then(user => console.log('User saved:', user))
.catch(err => console.error('Error saving user:', err));
Test your understanding of this topic:
Learn to work with PostgreSQL using Sequelize ORM for Node.js applications
Content by: Sachin Patel
Node.js Developer
PostgreSQL is a powerful, open-source relational database system. Sequelize is a promise-based Node.js ORM for PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server.
// Install dependencies
npm install sequelize pg pg-hstore
// Database configuration
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'postgres',
logging: false
});
// Test connection
async function testConnection() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
testConnection();
// Define a Model
const { DataTypes } = require('sequelize');
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
age: {
type: DataTypes.INTEGER,
validate: {
min: 0,
max: 120
}
}
}, {
timestamps: true
});
// Sync the model with database
sequelize.sync({ force: true })
.then(() => {
console.log('Database synced');
})
.catch(err => {
console.error('Error syncing database:', err);
});
Test your understanding of this topic:
Master Create, Read, Update, and Delete operations with both MongoDB and PostgreSQL
Content by: Parth Patel
Node.js Developer
// Create (C)
const createUser = async (userData) => {
try {
const user = new User(userData);
const savedUser = await user.save();
return savedUser;
} catch (error) {
throw error;
}
};
// Read (R)
const getAllUsers = async () => {
try {
const users = await User.find();
return users;
} catch (error) {
throw error;
}
};
const getUserById = async (id) => {
try {
const user = await User.findById(id);
return user;
} catch (error) {
throw error;
}
};
const getUserByEmail = async (email) => {
try {
const user = await User.findOne({ email });
return user;
} catch (error) {
throw error;
}
};
// Update (U)
const updateUser = async (id, updateData) => {
try {
const user = await User.findByIdAndUpdate(id, updateData, { new: true });
return user;
} catch (error) {
throw error;
}
};
// Delete (D)
const deleteUser = async (id) => {
try {
const user = await User.findByIdAndDelete(id);
return user;
} catch (error) {
throw error;
}
};
// Advanced queries
const getUsersByAge = async (minAge, maxAge) => {
try {
const users = await User.find({
age: { $gte: minAge, $lte: maxAge }
});
return users;
} catch (error) {
throw error;
}
};
const searchUsers = async (searchTerm) => {
try {
const users = await User.find({
$or: [
{ name: { $regex: searchTerm, $options: 'i' } },
{ email: { $regex: searchTerm, $options: 'i' } }
]
});
return users;
} catch (error) {
throw error;
}
};
// Create (C)
const createUser = async (userData) => {
try {
const user = await User.create(userData);
return user;
} catch (error) {
throw error;
}
};
// Read (R)
const getAllUsers = async () => {
try {
const users = await User.findAll();
return users;
} catch (error) {
throw error;
}
};
const getUserById = async (id) => {
try {
const user = await User.findByPk(id);
return user;
} catch (error) {
throw error;
}
};
const getUserByEmail = async (email) => {
try {
const user = await User.findOne({ where: { email } });
return user;
} catch (error) {
throw error;
}
};
// Update (U)
const updateUser = async (id, updateData) => {
try {
const user = await User.findByPk(id);
if (user) {
await user.update(updateData);
return user;
}
return null;
} catch (error) {
throw error;
}
};
// Delete (D)
const deleteUser = async (id) => {
try {
const user = await User.findByPk(id);
if (user) {
await user.destroy();
return user;
}
return null;
} catch (error) {
throw error;
}
};
// Advanced queries
const { Op } = require('sequelize');
const getUsersByAge = async (minAge, maxAge) => {
try {
const users = await User.findAll({
where: {
age: {
[Op.between]: [minAge, maxAge]
}
}
});
return users;
} catch (error) {
throw error;
}
};
const searchUsers = async (searchTerm) => {
try {
const users = await User.findAll({
where: {
[Op.or]: [
{ name: { [Op.iLike]: `%${searchTerm}%` } },
{ email: { [Op.iLike]: `%${searchTerm}%` } }
]
}
});
return users;
} catch (error) {
throw error;
}
};
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 4