NoSQL Database tutorial with examples using CRUD operations

 In this tutorial, we will go over how to use a NoSQL database (specifically MongoDB) with CRUD (Create, Read, Update, Delete) operations. MongoDB is one of the most popular NoSQL databases, and it stores data in a flexible, JSON-like format, making it highly suitable for scalable applications.

We'll use Node.js and MongoDB to demonstrate how to perform CRUD operations. The steps will include:

  1. Setting up MongoDB
  2. Connecting to MongoDB with Node.js
  3. Performing CRUD operations using MongoDB in a Node.js environment

Prerequisites

  1. MongoDB installed: If you don't have MongoDB installed, you can follow MongoDB installation guide.
  2. Node.js installed: You can download and install Node.js from here.
  3. A text editor like VSCode, Sublime, or any IDE of your choice.

1. Setting Up MongoDB and Node.js

First, let's set up the project folder and install the necessary dependencies.

1.1. Create Project Folder and Initialize Node.js Project

Open your terminal/command prompt, and execute the following commands:

bash
mkdir mongo-crud cd mongo-crud npm init -y

This will create a new Node.js project with a package.json file.

1.2. Install Dependencies

You need to install the following dependencies:

  • express: To handle HTTP requests.
  • mongoose: To interact with MongoDB.
  • body-parser: To parse incoming request bodies (useful for POST/PUT requests).

Run this command to install the dependencies:

bash
npm install express mongoose body-parser

2. Setting Up MongoDB Database Connection with Mongoose

2.1. Create a MongoDB Connection File

In the root directory, create a file called db.js to manage the MongoDB connection.

javascript
// db.js const mongoose = require('mongoose'); const url = 'mongodb://localhost:27017/your-database'; // Change 'your-database' to your database name mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('MongoDB connected successfully'); }) .catch((err) => { console.error('MongoDB connection error:', err); }); module.exports = mongoose;

This file sets up a connection to your local MongoDB server running on the default port 27017.


3. Create a Model for CRUD Operations

Now, we’ll create a Todo model to interact with the database.

3.1. Create todo.model.js

Inside your project folder, create a models folder and create a file called todo.model.js inside it. This file defines the structure of your Todo item.

javascript
// models/todo.model.js const mongoose = require('mongoose'); // Define a Schema for Todo const todoSchema = new mongoose.Schema({ title: { type: String, required: true }, completed: { type: Boolean, default: false }, }, { timestamps: true }); // Create a model based on the schema const Todo = mongoose.model('Todo', todoSchema); module.exports = Todo;

This schema defines a simple Todo item with a title and completed field. The timestamps option automatically adds createdAt and updatedAt fields to each document.


4. Set Up CRUD Operations in Express

Now that we have our database connected and model defined, let’s create an Express API to handle CRUD operations.

4.1. Create server.js File

Create a file called server.js in your root project directory. This file will handle all your routes.

javascript
// server.js const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('./db'); // Import database connection const Todo = require('./models/todo.model'); // Import Todo model const app = express(); const port = 3000; // Middleware app.use(bodyParser.json()); // Create - Add a new Todo app.post('/todos', async (req, res) => { const { title, completed } = req.body; try { const todo = new Todo({ title, completed }); const savedTodo = await todo.save(); res.status(201).json(savedTodo); } catch (err) { res.status(500).json({ message: 'Error creating Todo', error: err }); } }); // Read - Get all Todos app.get('/todos', async (req, res) => { try { const todos = await Todo.find(); res.json(todos); } catch (err) { res.status(500).json({ message: 'Error fetching Todos', error: err }); } }); // Read - Get a Todo by ID app.get('/todos/:id', async (req, res) => { const { id } = req.params; try { const todo = await Todo.findById(id); if (!todo) return res.status(404).json({ message: 'Todo not found' }); res.json(todo); } catch (err) { res.status(500).json({ message: 'Error fetching Todo', error: err }); } }); // Update - Update a Todo by ID app.put('/todos/:id', async (req, res) => { const { id } = req.params; const { title, completed } = req.body; try { const updatedTodo = await Todo.findByIdAndUpdate(id, { title, completed }, { new: true }); if (!updatedTodo) return res.status(404).json({ message: 'Todo not found' }); res.json(updatedTodo); } catch (err) { res.status(500).json({ message: 'Error updating Todo', error: err }); } }); // Delete - Delete a Todo by ID app.delete('/todos/:id', async (req, res) => { const { id } = req.params; try { const deletedTodo = await Todo.findByIdAndDelete(id); if (!deletedTodo) return res.status(404).json({ message: 'Todo not found' }); res.json({ message: 'Todo deleted' }); } catch (err) { res.status(500).json({ message: 'Error deleting Todo', error: err }); } }); // Start server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });

CRUD Endpoints

  • Create (POST /todos): Adds a new Todo to the database.
  • Read (GET /todos): Fetches all Todos.
  • Read (by ID) (GET /todos/:id): Fetches a single Todo by its ID.
  • Update (PUT /todos/:id): Updates a Todo by its ID.
  • Delete (DELETE /todos/:id): Deletes a Todo by its ID.

5. Testing CRUD Operations

5.1. Start the Server

Run the following command to start your Express server:

bash
node server.js

The server will start on http://localhost:3000.

5.2. Testing Using Postman or CURL

You can use Postman or CURL to test your API endpoints.

  1. Create a Todo (POST request)
  • URL: http://localhost:3000/todos
  • Body (JSON):
json
{ "title": "Learn MongoDB", "completed": false }
  1. Get All Todos (GET request)
  • URL: http://localhost:3000/todos
  1. Get Todo by ID (GET request)
  • URL: http://localhost:3000/todos/{id}
  1. Update Todo (PUT request)
  • URL: http://localhost:3000/todos/{id}
  • Body (JSON):
json
{ "title": "Learn MongoDB and Node.js", "completed": true }
  1. Delete Todo (DELETE request)
  • URL: http://localhost:3000/todos/{id}

6. Conclusion

You have now created a simple MongoDB-based CRUD application using Node.js, Express, and Mongoose! Here's a summary of the steps:

  • Set up MongoDB and connected it to Node.js using Mongoose.
  • Created a Todo model to define the structure of our data.
  • Implemented CRUD operations (Create, Read, Update, Delete) in Express routes.
  • Used Postman or CURL to test the API.

This is a basic example that can be extended with authentication, validation, and other advanced features as needed.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics