I’ll show you how to connect Node.js to a database. We are going to walk through the process of connecting MongoDB in this guide. It’s super easy, trust me.
First, you need MongoDB and Node.js set up. If you don’t have Node.js, download it via official site. MongoDB can be used locally or on the cloud using Atlas.
Why would you even want to use this database with Node? Well, Node.js is fast, and they work well together. MongoDB handles big amounts of data without slowing down, and that’s great for apps.
To get started, here’s what you need:
- Node.js installed.
- MongoDB, either local to Atlas.
Setup the Project
First, let’s make a Node.js app. Open up the terminal/CMD and run:
mkdir myapp
cd myapp
npm init -y
Now you got your project.
Next, we’ll install Mongoose. It’s a tool to talk to MongoDB:
npm install mongoose
Connect the Database
Now, create a file named app.js. Then add this code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', (error) => console.log('Error connecting:', error));
db.once('open', () => console.log('Connected to MongoDB!'));
That connects us to MongoDB. Simple stuff.
Now you can do basic database stuff. Create, read, update, delete. Here’s how.
Define the Schema and Model
First, you need a schema. It’s how you define what data looks like. I’ll show you an example for users:
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
});
This is the structure for user data. We make it into a model like this:
const User = mongoose.model('User', userSchema);
Create Data
You can create a user by doing this:
const newUser = new User({
name: 'John Doe',
email: 'john@example.com',
});
newUser.save((err) => {
if (err) console.log('Error saving user:', err);
else console.log('User saved!');
});
Read Data
Easy, right? Let’s read some data. Use find()
like this:
User.find({ name: 'John Doe' }, (err, users) => {
if (err) console.log('Error finding user:', err);
else console.log('Users found:', users);
});
Update Data
Now, let’s update a user:
User.updateOne(
{ email: 'john@example.com' },
{ $set: { name: 'John Smith' } },
(err, res) => {
if (err) console.log('Error updating:', err);
else console.log('User updated:', res);
}
);
Delete Data
To delete someone, use deleteOne()
like this:
User.deleteOne({ email: 'john@example.com' }, (err) => {
if (err) console.log('Error deleting:', err);
else console.log('User deleted!');
});
Troubleshooting Common Errors
Sometimes things break. Don’t worry, though. Check for these common issues:
- Wrong MongoDB URI: Double-check it.
- Network issues: Make sure MongoDB’s running.
- Atlas problems: Make sure your login is right.
You can handle errors with this:
db.on('error', console.error.bind(console, 'Connection error:'));
db.once('open', () => console.log('Connected to MongoDB!'));
Performance Tips
Speed up things with indexes. They make searching faster:
userSchema.index({ email: 1 });
Also, limit the amount of data MongoDB sends back:
User.find().limit(10);
Use Aggregation for Complex Queries
MongoDB’s aggregation tool helps with complex searches:
User.aggregate([
{ $match: { name: 'John Doe' } },
{ $group: { _id: '$name', count: { $sum: 1 } } }
]);
Use Transactions for Safe Changes
Want to make sure your database changes work together? MongoDB supports transactions:
const session = await mongoose.startSession();
session.startTransaction();
await User.create([{ name: 'Jane Doe' }], { session });
await session.commitTransaction();
That’s all! Connecting Node.js to MongoDB is straightforward. With Mongoose, you can do almost anything with your data.
Previous Lesson
Day 26: Express.js REST API Tutorial
Next Lesson
Day 28: Authentication in Node.js
Pingback: Authentication in Node.js - Equitem