Hello, I'm Arthur! I enjoy exploring backend development, programming, and technologies that help developers build reliable applications.
Most modern applications need a backend to store information, manage users, and process requests. A REST API makes communication between frontend applications and databases much easier.
In this tutorial, we'll build a simple REST API using Node.js, Express, and MongoDB.
1. Create a Node.js Project
First, create a new project:
mkdir node-mongodb-api
cd node-mongodb-api
npm init -y
Install the required packages:
npm install express mongoose dotenv
npm install --save-dev nodemon
We will use:
- Express for handling HTTP requests.
- Mongoose for MongoDB integration.
- Dotenv for managing environment variables.
- Nodemon for automatic server restarts during development.
2. Set Up the Project Structure
Create the following files:
node-mongodb-api/
│
├── models/
│ └── User.js
│
├── .env
├── server.js
└── package.json
Keeping models and server logic separate makes the project easier to maintain.
3. Connect Node.js to MongoDB
Open server.js and add:
const express = require("express");
const mongoose = require("mongoose");
require("dotenv").config();
const app = express();
app.use(express.json());
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log("MongoDB connected"))
.catch(error => console.error(error));
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Create a .env file:
MONGO_URI=mongodb://127.0.0.1:27017/mydatabase
This example assumes MongoDB is running locally. Never commit your .env file to a public repository.
4. Create a User Model
Create models/User.js:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
age: {
type: Number,
min: 1
}
});
module.exports = mongoose.model("User", userSchema);
The schema defines the structure of user documents stored in MongoDB.
5. Build the API Endpoints
Import the User model into server.js:
const User = require("./models/User");
Create a User
app.post("/users", async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (error) {
res.status(400).json({
message: error.message
});
}
});
Get All Users
app.get("/users", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({
message: error.message
});
}
});
Get a Single User
app.get("/users/:id", async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({
message: "User not found"
});
}
res.json(user);
} catch (error) {
res.status(400).json({
message: "Invalid user ID"
});
}
});
These endpoints demonstrate basic Create and Read operations.
6. Test the API
Start the development server:
npx nodemon server.js
You can test the endpoints using Postman or another API testing tool.
For example, send a POST request to:
http://localhost:3000/users
With this JSON body:
{
"name": "Alex",
"email": "alex@example.com",
"age": 25
}
If the request is successful, the API will return the newly created user.
7. Important Improvements for Production
The example above is a starting point. A production API needs additional protections and improvements:
- Validate request data before saving it.
- Add authentication and authorization.
- Use pagination for large datasets.
- Handle duplicate email errors.
- Add rate limiting.
- Use HTTPS.
- Store secrets securely.
- Implement proper logging and monitoring.
Planning Infrastructure for Backend Applications
For applications involving machine learning, AI workloads, or GPU-intensive data processing, developers can explore Seimaxim GPU Dedicated Servers for dedicated GPU computing resources.
Choosing suitable CPU, RAM, storage, and network capacity helps support application workloads as traffic increases.
Final Thoughts
Building a REST API with Node.js and MongoDB is a useful way to understand backend development.
You have now created a basic API, connected a database, defined a user model, and implemented endpoints for retrieving and creating records.
The next step is to add update and delete operations, authentication, and automated tests.
For applications that need dedicated computing infrastructure as they grow, Seimaxim Server Hosting is another option worth evaluating.
Keep experimenting with small backend projects. Practical experience is one of the best ways to improve your development skills.
Top comments (0)