A comprehensive guide to integrating MongoDB Atlas with your RESTful API, covering database connection setup, schema modeling with mongoose, and implementing CRUD operations. Perfect for developers looking to add persistent data storage to their Node.js applications.
7 min read
In the previous two parts of this series, we covered setting up a basic RESTful API and testing it locally. This third part will focus on integrating MongoDB Atlas with our API and using mongoose to manage our database operations.
We'll learn how to:
Before starting, you'll need:
We'll start by installing the necessary packages for MongoDB integration:
npm i dotenv mongoose
These packages will help us:
We'll organize our project with the following structure:
To begin integrating with MongoDB Atlas:
First, create a new file called db.js
in your project's root directory. This file will handle the MongoDB connection setup using mongoose:
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI);
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
};
module.exports = connectDB;
Next, we'll create our first schema model to define the structure of our data. Create a new file in the models directory:
Create a file called user.model.js
with the following schema definition:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
match: [/.+\@.+\..+/, 'Please enter a valid email']
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);
This schema defines the structure for our User model with basic validation and required fields. Now we can use this model to interact with our MongoDB database through mongoose.
Now that we have our database connection and model set up, let's implement the CRUD (Create, Read, Update, Delete) operations in our API. We'll create controller functions that utilize our User model to interact with MongoDB.
Create a new file called user.controller.js
in your controllers directory: