Building a CRUD Application with Node.js and MongoDB
Node.js and MongoDB form a popular technology stack for building modern web applications. This article will guide you through creating a simple CRUD (Create, Read, Update, Delete) application using Node.js and MongoDB.
Prerequisites
Before you start, ensure you have the following installed:
Node.js and npm (Node Package Manager)
MongoDB (either locally or using a cloud service like MongoDB Atlas)
A code editor like Visual Studio Code
Setting Up the Project
Step 1: Initialize the Project
First, create a new directory for your project and initialize a Node.js project:
mkdirnode-mongo-crudcdnode-mongo-crudnpminit-y
Step 2: Install Dependencies
Install the necessary dependencies:
npminstallexpressmongoosebody-parser
express: A minimal and flexible Node.js web application framework.
mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.
body-parser: Middleware to parse incoming request bodies in a middleware before your handlers, available under the req.body property.
Create a routes/userRoutes.js file and define the CRUD routes:
constexpress=require('express');constUser=require('../models/user');constrouter=express.Router();// Create a new userrouter.post('/users',async (req, res) => {try {constuser=newUser(req.body);awaituser.save();res.status(201).send(user); } catch (error) {res.status(400).send(error); }});// Get all usersrouter.get('/users',async (req, res) => {try {constusers=awaitUser.find();res.status(200).send(users); } catch (error) {res.status(500).send(error); }});// Get a single user by IDrouter.get('/users/:id',async (req, res) => {try {constuser=awaitUser.findById(req.params.id);if (!user) {returnres.status(404).send(); }res.status(200).send(user); } catch (error) {res.status(500).send(error); }});// Update a userrouter.put('/users/:id',async (req, res) => {try {constuser=awaitUser.findByIdAndUpdate(req.params.id,req.body, { new:true, runValidators:true });if (!user) {returnres.status(404).send(); }res.status(200).send(user); } catch (error) {res.status(400).send(error); }});// Delete a userrouter.delete('/users/:id',async (req, res) => {try {constuser=awaitUser.findByIdAndDelete(req.params.id);if (!user) {returnres.status(404).send(); }res.status(200).send(user); } catch (error) {res.status(500).send(error); }});module.exports= router;
Step 6: Set Up the Express Application
Create an app.js file to set up the Express application:
constexpress=require('express');constmongoose=require('mongoose');constbodyParser=require('body-parser');constuserRoutes=require('./routes/userRoutes');constapp=express();constport=process.env.PORT||3000;app.use(bodyParser.json());app.use(userRoutes);mongoose.connect('mongodb://localhost:27017/nodecrud', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then(() => {console.log('Connected to MongoDB');app.listen(port, () => {console.log(`Server running on port ${port}`); }); }).catch(error => {console.error('Connection error',error.message); });
Step 7: Run the Application
Make sure your MongoDB server is running. You can start your MongoDB server using:
mongod
Then, run your Node.js application:
nodeapp.js
Your application should now be running on http://localhost:3000.
Testing the CRUD Endpoints
Use a tool like Postman or curl to test the endpoints:
Create a new user:
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Alice","email":"alice@example.com"}'
Get all users:
curl-XGEThttp://localhost:3000/users
Get a user by ID:
curl-XGEThttp://localhost:3000/users/<user_id>
Update a user:
curl -X PUT http://localhost:3000/users/<user_id> -H "Content-Type: application/json" -d '{"name":"Alice Updated","email":"alice.updated@example.com"}'
Delete a user:
curl-XDELETEhttp://localhost:3000/users/<user_id>
Conclusion
You've now built a complete CRUD application using Node.js and MongoDB. This application serves as a basic template that you can expand and customize to fit more complex requirements. With Node.js and MongoDB, you have the flexibility and scalability to build robust web applications. Happy coding!