Node.js and MongoDB: Building a CRUD Application

Nitin Rachabathuni
3 min readMar 11, 2024

--

Creating a CRUD application with Node.js and MongoDB is an excellent way to understand how these technologies work together to build dynamic and scalable web applications. In this LinkedIn article, we’ll walk through the process of setting up a simple CRUD (Create, Read, Update, Delete) application. This example will illustrate how you can leverage Node.js for server-side scripting and MongoDB as a NoSQL database for storing and manipulating data.

Prerequisites

Before we dive into the coding part, ensure you have the following installed on your computer:

  • Node.js
  • MongoDB
  • A code editor like Visual Studio Code

Step 1: Initialize a New Node.js Project

First, create a new directory for your project and navigate into it:

mkdir nodejs-mongodb-crud
cd nodejs-mongodb-crud

Then, initialize a new Node.js project:

npm install express mongoose body-parser

Step 3: Connect to MongoDB

Create a file named database.js in your project directory and add the following code to connect to MongoDB using Mongoose:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/nodejsMongoDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("Connected successfully to MongoDB");
});

Replace 'mongodb://localhost:27017/nodejsMongoDB' with your MongoDB URI if you are using a cloud instance like MongoDB Atlas.

Step 4: Define a Mongoose Model

Create a new file named model.js and define a schema for our CRUD operations:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const itemSchema = new Schema({
name: String,
description: String,
price: Number,
});

const Item = mongoose.model('Item', itemSchema);

module.exports = Item;

Step 5: Implement CRUD Operations

Now, let’s set up our Express server in a file named app.js and implement the CRUD operations

const express = require('express');
const bodyParser = require('body-parser');
const Item = require('./model'); // Import the model
require('./database'); // Connect to MongoDB

const app = express();
const port = 3000;

app.use(bodyParser.json());

// Create
app.post('/items', async (req, res) => {
const item = new Item(req.body);
try {
await item.save();
res.status(201).send(item);
} catch (error) {
res.status(400).send(error);
}
});

// Read all items
app.get('/items', async (req, res) => {
try {
const items = await Item.find({});
res.send(items);
} catch (error) {
res.status(500).send(error);
}
});

// Update
app.patch('/items/:id', async (req, res) => {
try {
const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!item) {
return res.status(404).send();
}
res.send(item);
} catch (error) {
res.status(400).send(error);
}
});

// Delete
app.delete('/items/:id', async (req, res) => {
try {
const item = await Item.findByIdAndDelete(req.params.id);
if (!item) {
return res.status(404).send();
}
res.send(item);
} catch (error) {
res.status(500).send(error);
}
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Step 6: Testing Your Application

You can test your CRUD application using tools like Postman or Curl. Here are the endpoints you’ve created:

  • POST /items to create a new item
  • GET /items to read all items
  • PATCH /items/:id to update an item by id
  • DELETE /items/:id to delete an item by id

Conclusion

You’ve now created a basic CRUD application using Node.js and MongoDB! This setup serves as a foundation for building more complex web applications. Experiment with expanding this application by adding more features, such as user authentication or more complex data relationships.

Remember, the key to mastering web development is practice and continuous learning. Keep experimenting with different aspects of Node.js and MongoDB, and you’ll become proficient in building back-end services for your applications.

Thank you for reading my article! For more updates and useful information, feel free to connect with me on LinkedIn and follow me on Twitter. I look forward to engaging with more like-minded professionals and sharing valuable insights.

--

--

Nitin Rachabathuni
Nitin Rachabathuni

Written by Nitin Rachabathuni

Seeking freelance opportunities | React.js, Next.js, Vue.js, Angular, Node.js, Commercetools, Merchant Center, Frontastic, Azure, AWS | +91-9642222836

No responses yet