Connecting to a Database in Node.js and Express.
Course Title: Modern JavaScript Programming: From Fundamentals to Full-Stack Development Section Title: Back-End Development with Node.js and Express Topic: Connecting to a database (MongoDB or PostgreSQL) and handling CRUD operations
Overview
In this topic, we'll explore how to connect to a database and perform CRUD (Create, Read, Update, Delete) operations using Node.js and Express. We'll cover two popular databases, MongoDB and PostgreSQL, and learn how to interact with them using popular Node.js libraries.
Why Databases Matter
Databases are a crucial part of any web application, as they store and manage data that's used to provide a rich user experience. In this topic, we'll learn how to connect to a database, perform CRUD operations, and integrate our Express application with the database to store and retrieve data.
Connecting to a MongoDB Database
For MongoDB, we'll use the Mongoose library, which provides a simple and intuitive way to interact with MongoDB.
Installing Mongoose
npm install mongoose
Connecting to a MongoDB Database
// Import Mongoose
const mongoose = require('mongoose');
// Connection string
const mongoUrl = 'mongodb://localhost:27017/mydatabase';
// Connect to MongoDB
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
// Create a schema
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
// Create a model
const User = mongoose.model('User', userSchema);
Connecting to a PostgreSQL Database
For PostgreSQL, we'll use the pg library, which provides a simple and efficient way to interact with PostgreSQL.
Installing pg
npm install pg
Connecting to a PostgreSQL Database
// Import pg
const { Pool } = require('pg');
// Connection string
const pgUrl = 'postgresql://username:password@localhost:5432/mydatabase';
// Create a pool
const pool = new Pool({
connectionString: pgUrl
});
CRUD Operations
Once we've connected to our database, we can perform CRUD operations to manage data. Let's use Mongoose to perform CRUD operations on a MongoDB database.
Create
// Create a new user
const user = new User({ name: 'John Doe', age: 30 });
user.save((err, user) => {
if (err) console.error(err);
console.log(user);
});
Read
// Find all users
User.find((err, users) => {
if (err) console.error(err);
console.log(users);
});
// Find a user by ID
User.findById('5f676a1a34b76f0ec0a76a7d', (err, user) => {
if (err) console.error(err);
console.log(user);
});
Update
// Update a user
User.findByIdAndUpdate('5f676a1a34b76f0ec0a76a7d', { name: 'Jane Doe' }, (err, user) => {
if (err) console.error(err);
console.log(user);
});
Delete
// Delete a user
User.findByIdAndRemove('5f676a1a34b76f0ec0a76a7d', (err, user) => {
if (err) console.error(err);
console.log(user);
});
Integrating with Express
Once we've connected to our database and performed CRUD operations, we can integrate our Express application with the database to store and retrieve data.
Adding a User
// Import Express
const express = require('express');
const app = express();
// Import Mongoose
const User = require('./models/user');
// Create a new user
app.post('/users', (req, res) => {
const user = new User({ name: req.body.name, age: req.body.age });
user.save((err, user) => {
if (err) console.error(err);
res.json(user);
});
});
Getting All Users
// Get all users
app.get('/users', (req, res) => {
User.find((err, users) => {
if (err) console.error(err);
res.json(users);
});
});
Conclusion
In this topic, we've learned how to connect to a database (MongoDB or PostgreSQL) and perform CRUD operations using Node.js and Express. We've also seen how to integrate our Express application with the database to store and retrieve data. For more information on MongoDB and Mongoose, please visit the Mongoose documentation. For more information on PostgreSQL and pg, please visit the pg documentation.
Practical Takeaways
- Connect to a database using Mongoose or pg
- Perform CRUD operations using Mongoose or pg
- Integrate an Express application with a database
- Use Express to create, read, update, and delete data in a database
What's Next?
In the next topic, we'll learn about the importance of testing in modern JavaScript applications.
Do you have any questions or need help with anything? Please leave a comment below.
Images

Comments