Creating a Node.js Project with MongoDB for CRUD Operations

I'm Ogunuyo Ogheneruemu Brown, a senior software developer. I specialize in DApp apps, fintech solutions, nursing web apps, fitness platforms, and e-commerce systems. Throughout my career, I've delivered successful projects, showcasing strong technical skills and problem-solving abilities. I create secure and user-friendly fintech innovations. Outside work, I enjoy coding, swimming, and playing football. I'm an avid reader and fitness enthusiast. Music inspires me. I'm committed to continuous growth and creating impactful software solutions. Let's connect and collaborate to make a lasting impact in software development.
In this comprehensive guide, we'll walk through the process of creating a Node.js project that connects to a MongoDB database and performs various CRUD (Create, Read, Update, Delete) operations. We'll use the Express framework for building our API and Mongoose for interacting with MongoDB.
To download and install MongoDB using Homebrew on macOS, follow these short steps:
Update Homebrew:
brew updateInstall MongoDB:
brew install mongodb-communityStart MongoDB:
brew services start mongodb/brew/mongodb-community
That's it! MongoDB is now installed on your macOS system using Homebrew.
To download and install MongoDB on Windows using the terminal, follow these short steps:
Download MongoDB:
curl -O https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-5.0.3.zipExtract the ZIP file:
tar -xvzf mongodb-windows-x86_64-5.0.3.zipMove MongoDB to a desired location (e.g., C:\mongodb):
mv mongodb-windows-x86_64-5.0.3 C:\mongodbAdd MongoDB to the system's PATH environment variable:
setx PATH "%PATH%;C:\mongodb\bin"
That's it! MongoDB is now installed on your Windows system. You can verify the installation by opening a new terminal window and running mongod --version.
Step 1: Set Up Your Node.js Project
First, we need to initialize a new Node.js project and install the required dependencies.
Initialize the Project:
mkdir my-mongo-app cd my-mongo-app npm init -yInstall Dependencies:
npm install express mongoose
Step 2: Create the Project Structure
Next, create the necessary files and directories for our project.
Create the Main File and Model Directory:
touch index.js mkdir models touch models/User.js
Step 3: Set Up MongoDB Connection
In index.js, we'll set up the Express server and connect to MongoDB using Mongoose.
Configure MongoDB Connection:
const express = require('express'); const mongoose = require('mongoose'); const app = express(); // Middleware to parse JSON bodies app.use(express.json()); // MongoDB connection mongoose.connect('mongodb://localhost:27017/mydatabase') .then(() => { console.log('Connected to MongoDB'); }) .catch(err => { console.error('Error connecting to MongoDB', err); }); const User = require('./models/User'); // Routes for CRUD operations app.post('/users', async (req, res) => { try { const user = new User(req.body); await user.save(); res.status(201).send(user); } catch (error) { res.status(400).send(error); } }); app.get('/users', async (req, res) => { try { const users = await User.find(); res.status(200).send(users); } catch (error) { res.status(500).send(error); } }); app.get('/users/:id', async (req, res) => { try { const user = await User.findById(req.params.id); if (!user) { return res.status(404).send(); } res.status(200).send(user); } catch (error) { res.status(500).send(error); } }); app.patch('/users/:id', async (req, res) => { try { const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if (!user) { return res.status(404).send(); } res.status(200).send(user); } catch (error) { res.status(400).send(error); } }); app.delete('/users/:id', async (req, res) => { try { const user = await User.findByIdAndDelete(req.params.id); if (!user) { return res.status(404).send(); } res.status(200).send(user); } catch (error) { res.status(500).send(error); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Step 4: Define the User Model
Create the User model schema in models/User.js.
Define the Schema:
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, email: { type: String, required: true, trim: true, unique: true }, age: { type: Number, default: 0 } }); const User = mongoose.model('User', userSchema); module.exports = User;
Step 5: Test Your API
Start your Node.js server and test the API endpoints using Postman or curl.
Start the Server:
node index.jsTest the API Endpoints:
Create a New User:
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe", "email":"john@example.com", "age":30}' http://localhost:3000/usersGet All Users:
curl http://localhost:3000/usersGet a User by ID:
curl http://localhost:3000/users/<user_id>Update a User by ID:
curl -X PATCH -H "Content-Type: application/json" -d '{"name":"Jane Doe"}' http://localhost:3000/users/<user_id>Delete a User by ID:
curl -X DELETE http://localhost:3000/users/<user_id>
Note:
Ensure that MongoDB is running on your system. You can start MongoDB using the following command:
mongod
Setting Up Postman for API Testing
To ensure that your POST request is properly recognized as containing JSON data, you need to set the Content-Type header to application/json in Postman. Here’s a step-by-step explanation:
Open Postman and Create a New Request:
Open Postman.
Click the
+button to create a new request tab.Select
POSTfrom the dropdown menu next to the URL input field.Enter the URL
http://localhost:3000/usersin the URL input field.
Set the Headers:
Click on the Headers tab, which is located right under the URL input field.
If there isn’t already a header named
Content-Type, you need to add one.To add a new header:
Click the
+button on the right side of the Headers tab to add a new key-value pair.In the Key field, enter
Content-Type.In the Value field, enter
application/json.
It should look like this:
| Key | Value | | --- | --- | | Content-Type | application/json |
Set the Request Body:
Click on the Body tab, which is next to the Headers tab.
Select the raw radio button.
In the dropdown menu next to the raw option, select
JSON (application/json).Enter your JSON payload in the text area. For example:
{ "name": "John Doe", "email": "john@example.com", "age": 30 }
Send the Request:
- After setting the headers and body, click the Send button to send your request to the server.
Visual Guide
Open Postman and Create a New Request:
Set the Headers:
Set the Request Body:
Send the Request:
Summary
By following these steps, you can successfully create a Node.js project with MongoDB and implement CRUD operations using Express and Mongoose. Additionally, you now know how to set up and test your API endpoints using Postman. This guide should provide a solid foundation for building and testing your own APIs. If you encounter any issues, checking the server logs can provide additional insights into what might be going wrong.




