0% found this document useful (0 votes)
56 views24 pages

MongoDB and Node.js Integration Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views24 pages

MongoDB and Node.js Integration Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Table of Contents

1. SQL vs NoSQL
2. MongoDB Essentials
3. Connecting [Link] to MongoDB
4. Full CRUD Operations
5. Edge Cases & Best Practices

1. SQL vs NoSQL

Tables vs Documents

SQL (Relational Databases)

Data stored in tables with rows and columns


Fixed schema (structure must be defined before inserting data)
Relationships between tables using foreign keys
Examples: MySQL, PostgreSQL, SQL Server

┌─────────────┬──────────┬─────────┐
│ user_id │ name │ email │
├─────────────┼──────────┼─────────┤
│ 1 │ John │ j@[Link] │
│ 2 │ Jane │ j@[Link] │
└─────────────┴──────────┴─────────┘

NoSQL (Non-Relational Databases)

Data stored as documents (like JSON objects)


Flexible schema (can add fields without changing structure)
No fixed relationships
Examples: MongoDB, CouchDB, DynamoDB

{
"_id": "507f1f77bcf86cd799439011",
"name": "John",
"email": "j@[Link]",
"age": 30,
"address": {
"city": "Kathmandu",
"country": "Nepal"
}
}

When MongoDB Fits Well

Good for MongoDB:

Flexible data structure : When your data structure changes frequently


Large-scale applications: Social media, content management systems
Real-time analytics : Logging, IoT data
Content management : Blogs, e-commerce with varying product attributes
User profiles: Different users may have different fields
Rapid development: Prototyping and MVP development

Real-world examples:

Facebook: Stores user posts, comments, likes


eBay: Product catalogs with varying attributes
Forbes: Article content and metadata
The Weather Channel: Weather data and forecasts

When SQL is Better

Good for SQL:

Financial transactions : Banking, accounting (ACID compliance critical)


Complex queries: Reports with multiple joins
Structured data : Inventory management, employee records
Data integrity: When relationships are critical
Mature applications: When schema is well-defined and stable
Real-world examples:

Banks: Transaction records, account balances


ERP systems: Enterprise resource planning
Hospital systems : Patient records with strict relationships

Industry Examples

Use Case Database Choice Reason

Social Media Feed MongoDB Flexible posts, comments, likes

Banking System SQL (PostgreSQL) Transaction integrity, ACID compliance

E-commerce Catalog MongoDB Products with varying attributes

Inventory Structured relationships, stock


SQL (MySQL)
Management tracking

Blog Platform MongoDB Flexible content structure

Financial Reports SQL Complex queries, joins

2. MongoDB Essentials

Core Concepts

Database

Container for collections


Like a folder that holds multiple collections
Example: myapp , ecommerce , blog

Collection

Group of documents (like a table in SQL)


No fixed schema
Example: users , products , orders

Document

Single record in a collection (like a row in SQL)


Stored as BSON (Binary JSON)
Example: A single user object

BSON (Binary JSON)

Binary representation of JSON


Supports more data types than JSON (Date, ObjectId, etc.)
Faster to parse than JSON

MongoDB Shell Commands

Basic Operations

// Show all databases


show dbs

// Switch to a database (creates if doesn't exist)


use myapp

// Show current database


db

// Show all collections in current database


show collections

// Drop current database


[Link]()
Collection Operations

// Create a collection (MongoDB creates it automatically when you insert)


// But you can also create explicitly:
[Link]("users")

// Drop a collection
[Link]()

// Get collection stats


[Link]()

Document Operations (CRUD in Shell)

CREATE (Insert)

// Insert one document


[Link]({
name: "John Doe",
email: "john@[Link]",
age: 30,
isActive: true,
createdAt: new Date()
})

// Insert multiple documents


[Link]([
{
name: "Jane Smith",
email: "jane@[Link]",
age: 25,
isActive: true
},
{
name: "Bob Johnson",
email: "bob@[Link]",
age: 35,
isActive: false
}
])

READ (Find)
// Find all documents
[Link]()

// Find with pretty print


[Link]().pretty()

// Find one document


[Link]({ name: "John Doe" })

// Find with filter


[Link]({ age: { $gt: 25 } }) // age greater than 25
[Link]({ isActive: true })

// Find with multiple conditions (AND)


[Link]({
age: { $gt: 25 },
isActive: true
})

// Find with OR condition


[Link]({
$or: [
{ age: { $gt: 30 } },
{ isActive: false }
]
})

// Select specific fields (projection)


[Link]({}, { name: 1, email: 1 }) // only name and email
[Link]({}, { name: 1, email: 1, _id: 0 }) // exclude _id

// Limit results
[Link]().limit(5)

// Skip results (pagination)


[Link]().skip(10).limit(5)

// Sort results
[Link]().sort({ age: 1 }) // ascending
[Link]().sort({ age: -1 }) // descending

// Count documents
[Link]({ isActive: true })

UPDATE
// Update one document
[Link](
{ name: "John Doe" }, // filter
{ $set: { age: 31 } } // update operation
)

// Update multiple documents


[Link](
{ isActive: false },
{ $set: { isActive: true } }
)

// Update operators
[Link](
{ name: "John Doe" },
{
$set: { age: 31 }, // set field
$inc: { loginCount: 1 }, // increment
$push: { tags: "premium" }, // add to array
$unset: { oldField: "" } // remove field
}
)

// Replace entire document


[Link](
{ name: "John Doe" },
{
name: "John Doe",
email: "newemail@[Link]",
age: 31
}
)

DELETE

// Delete one document


[Link]({ name: "John Doe" })

// Delete multiple documents


[Link]({ isActive: false })

// Delete all documents (be careful!)


[Link]({})

Common Query Operators


// Comparison Operators
[Link]({ age: { $gt: 25 } }) // greater than
[Link]({ age: { $gte: 25 } }) // greater than or equal
[Link]({ age: { $lt: 30 } }) // less than
[Link]({ age: { $lte: 30 } }) // less than or equal
[Link]({ age: { $ne: 25 } }) // not equal
[Link]({ age: { $in: [25, 30, 35] } }) // in array
[Link]({ age: { $nin: [25, 30] } }) // not in array

// Logical Operators
[Link]({ $and: [{ age: { $gt: 25 } }, { isActive: true }] })
[Link]({ $or: [{ age: { $gt: 30 } }, { isActive: false }] })
[Link]({ $not: { age: { $gt: 25 } } })

// Array Operators
[Link]({ tags: "premium" }) // array contains
[Link]({ tags: { $all: ["premium", "vip"] } }) // contains all
[Link]({ tags: { $size: 3 } }) // array size

3. Connecting [Link] to MongoDB

Installation

# Install Mongoose (ODM - Object Document Mapper)


npm install mongoose

# Or with yarn
yarn add mongoose

What is Mongoose?

Mongoose is an ODM (Object Document Mapper) for MongoDB and [Link]. It provides:

Schema definition
Data validation
Middleware hooks
Easy query building
Type casting

Basic Connection Setup

Create src/config/[Link] :

const mongoose = require('mongoose');

const connectDB = async () => {


try {
const conn = await [Link](
'mongodb+srv://<DB_USERNAME>:<DB_PASSWORD>@<CLUSTER_NAME>.[Link]/<DB_NAME>?retryWrites=true&w=majority'
);
[Link](`MongoDB Connected: ${[Link]}`);
} catch (error) {
[Link]('Database connection error:', [Link]);
[Link](1);
}
};

[Link] = connectDB;

Update [Link] :
const app = require('./src/app');
const connectDB = require('./src/config/database');

const PORT = [Link] || 3000;

// Connect to database first, then start server


connectDB().then(() => {
[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});
});

Schema & Model

Schema = Blueprint for documents (defines structure) Model = Constructor function that creates documents

Create src/models/[Link] :
const mongoose = require('mongoose');

// Define Schema
const userSchema = new [Link]({
name: {
type: String,
required: [true, 'Name is required'], // Custom error message
trim: true, // Remove whitespace
minlength: [2, 'Name must be at least 2 characters'],
maxlength: [50, 'Name cannot exceed 50 characters']
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true, // Ensures email is unique
lowercase: true, // Convert to lowercase
match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email'] // Email validation
},
age: {
type: Number,
min: [0, 'Age cannot be negative'],
max: [120, 'Age cannot exceed 120']
},
isActive: {
type: Boolean,
default: true // Default value
},
role: {
type: String,
enum: ['user', 'admin', 'moderator'], // Only these values allowed
default: 'user'
},
tags: [String], // Array of strings
address: {
city: String,
country: String
},
createdAt: {
type: Date,
default: [Link] // Automatically set when document is created
},
updatedAt: {
type: Date,
default: [Link]
}
}, {
timestamps: true // Automatically adds createdAt and updatedAt
});

// Create Model
const User = [Link]('User', userSchema);

[Link] = User;

Schema Types:

String , Number , Boolean , Date


Array , Object
[Link] (for references)
[Link] (any type)

Connecting to MongoDB Atlas (Cloud)

1. Create Account: Go to [Link]


2. Create Cluster: Free tier available
3. Get Connection String:
Click "Connect" on your cluster
Choose "Connect your application"
Copy the connection string
4. Set Environment Variable:

# Create .env file


MONGODB_URI=mongodb+srv://username:password@[Link]/myapp?retryWrites=true&w=majority
PORT=3000

Install dotenv:

npm install dotenv

Update [Link] :

require('dotenv').config(); // Load environment variables


const app = require('./src/app');
const connectDB = require('./src/config/database');
// ... rest of code

4. Full CRUD Operations


CRUD = Create, Read, Update, Delete. This section shows how to build these operations step by step.

What We're Building

A User Management API with these endpoints:

POST /api/users - Create a new user


GET /api/users - Get all users
GET /api/users/:id - Get one user by ID
PUT /api/users/:id - Update a user
PUT /api/users/:id/renew - Renew user validity
DELETE /api/users/:id - Delete a user

Project Structure

First, create this folder structure:

randomizer/
├── src/
│ ├── config/
│ │ └── [Link] (Database connection)
│ ├── models/
│ │ └── [Link] (User schema/model)
│ ├── controllers/
│ │ └── [Link] (Business logic)
│ ├── routes/
│ │ └── [Link] (API routes)
│ ├── middleware/
│ │ └── [Link] (Error handling)
│ └── [Link] (Express app setup)
├── [Link] (Start server)
└── [Link]

Step 1: Create the Model

File: src/models/[Link]

A model defines what data a user can have.


const mongoose = require('mongoose');

// Define what a User document looks like


const userSchema = new [Link]({
unique_id: {
type: String,
required: true, // Must have this field
unique: true, // No two users can have same unique_id
trim: true // Remove extra spaces
},
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true, // No duplicate emails
lowercase: true, // Convert to lowercase
trim: true
},
contact: {
type: String,
required: true,
trim: true
},
membership_fee: {
type: Number,
required: true,
min: 0 // Cannot be negative
},
validity: {
type: Number,
required: true,
default: 0, // Default value if not provided
min: 0
}
}, {
timestamps: true // Automatically adds createdAt and updatedAt
});

// Create the User model


const User = [Link]('User', userSchema);

[Link] = User;

What this does:

Defines user fields and rules


required: true means the field is mandatory
unique: true prevents duplicates
timestamps: true adds createdAt and updatedAt

Step 2: Create Routes

File: src/routes/[Link]

Routes map URLs to controller functions.


const express = require('express');
const router = [Link]();

// Import controller functions


const {
createUser,
getUsers,
getUserById,
updateUser,
renewUser,
deleteUser
} = require('../controllers/userController');

// Define routes
[Link]('/', createUser); // Create user
[Link]('/', getUsers); // Get all users
[Link]('/:id', getUserById); // Get one user
[Link]('/:id', updateUser); // Update user
[Link]('/:id/renew', renewUser); // Renew validity
[Link]('/:id', deleteUser); // Delete user

[Link] = router;

What this does:

[Link]('/') handles POST requests to /api/users


[Link]('/:id') handles GET requests with an ID parameter
:id is a URL parameter (e.g., /api/users/123 )

Step 3: Create Controllers (CRUD Operations)

File: src/controllers/[Link]

Controllers contain the logic for each operation.

CREATE - Add a New User


const User = require('../models/User');

const createUser = async (req, res, next) => {


try {
// Get data from request body
const { unique_id, name, email, contact, membership_fee, validity } = [Link];

// Check if required fields are provided


if (!unique_id || !name || !email || !contact || membership_fee === undefined) {
return [Link](400).json({
success: false,
message: 'unique_id, name, email, contact, and membership_fee are required'
});
}

// Create new user in database


const user = await [Link]({
unique_id,
name,
email,
contact,
membership_fee,
validity: validity || 0 // Use 0 if not provided
});

// Send success response


[Link](201).json({
success: true,
message: 'User created successfully',
data: user
});
} catch (error) {
// Handle duplicate unique_id or email
if ([Link] === 11000) {
const field = [Link]([Link])[0];
return [Link](409).json({
success: false,
message: `${field} already exists`
});
}

// Handle validation errors


if ([Link] === 'ValidationError') {
const errors = [Link]([Link]).map(err => [Link]);
return [Link](400).json({
success: false,
message: [Link](', ')
});
}

// Pass other errors to error handler


next(error);
}
};

How to test:
POST [Link]
Content-Type: application/json

{
"unique_id": "USER001",
"name": "John Doe",
"email": "john@[Link]",
"contact": "1234567890",
"membership_fee": 1000,
"validity": 12
}

What happens:

1. Checks required fields


2. Creates the user in MongoDB
3. Returns the created user
4. Handles errors (duplicates, validation)

READ - Get All Users

const getUsers = async (req, res, next) => {


try {
// Find all users, sort by newest first
const users = await [Link]()
.select('-__v') // Exclude __v field
.sort({ createdAt: -1 }); // -1 = descending (newest first)

// Send response
[Link](200).json({
success: true,
count: [Link],
data: users
});
} catch (error) {
next(error);
}
};

How to test:

GET [Link]

What happens:

1. Fetches all users from the database


2. Sorts by creation date (newest first)
3. Returns the list

READ - Get One User by ID


const mongoose = require('mongoose');

const getUserById = async (req, res, next) => {


try {
// Get ID from URL parameter
const { id } = [Link];

// Check if ID is valid MongoDB ObjectId format


if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

// Find user by ID
const user = await [Link](id).select('-__v');

// Check if user exists


if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

// Send response
[Link](200).json({
success: true,
data: user
});
} catch (error) {
next(error);
}
};

How to test:

GET [Link]

What happens:

1. Validates the ID format


2. Finds the user by ID
3. Returns the user if found
4. Returns 404 if not found

UPDATE - Update User Information

const updateUser = async (req, res, next) => {


try {
// Get ID from URL and data from request body
const { id } = [Link];
const { name, email, contact } = [Link];

// Validate ID format
if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

// Build update object (only include fields that were provided)


const updateData = {};
const updateData = {};
if (name) [Link] = name;
if (email) [Link] = email;
if (contact) [Link] = contact;

// Check if at least one field is provided


if ([Link](updateData).length === 0) {
return [Link](400).json({
success: false,
message: 'Please provide name, email, or contact to update'
});
}

// Update user in database


// { new: true } = return updated document
// { runValidators: true } = run schema validators
const user = await [Link](
id,
updateData,
{ new: true, runValidators: true }
).select('-__v');

// Check if user exists


if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

// Send response
[Link](200).json({
success: true,
message: 'User updated successfully',
data: user
});
} catch (error) {
// Handle duplicate email
if ([Link] === 11000) {
return [Link](409).json({
success: false,
message: 'Email already exists'
});
}

// Handle validation errors


if ([Link] === 'ValidationError') {
const errors = [Link]([Link]).map(err => [Link]);
return [Link](400).json({
success: false,
message: [Link](', ')
});
}

next(error);
}
};

How to test:
PUT [Link]
Content-Type: application/json

{
"name": "John Updated",
"email": "[Link]@[Link]",
"contact": "9876543210"
}

What happens:

1. Validates the ID
2. Builds an update object from provided fields
3. Updates the user in the database
4. Returns the updated user
5. Handles errors (duplicate email, validation)

UPDATE - Renew User Validity

const renewUser = async (req, res, next) => {


try {
// Get ID from URL
const { id } = [Link];

// Validate ID format
if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

// Increment validity by 1
// $inc is MongoDB operator to increment a number
const user = await [Link](
id,
{ $inc: { validity: 1 } }, // Add 1 to validity
{ new: true, runValidators: true }
).select('-__v');

// Check if user exists


if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

// Send response
[Link](200).json({
success: true,
message: 'Validity renewed successfully',
data: user
});
} catch (error) {
next(error);
}
};

How to test:

PUT [Link]

What happens:
1. Validates the ID
2. Increments validity by 1
3. Returns the updated user

DELETE - Remove a User

const deleteUser = async (req, res, next) => {


try {
// Get ID from URL
const { id } = [Link];

// Validate ID format
if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

// Delete user from database


const user = await [Link](id);

// Check if user existed


if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

// Send response
[Link](200).json({
success: true,
message: 'User deleted successfully',
data: user
});
} catch (error) {
next(error);
}
};

How to test:

DELETE [Link]

What happens:

1. Validates the ID
2. Deletes the user from the database
3. Returns the deleted user data
4. Returns 404 if the user doesn't exist

Step 4: Complete Controller File

File: src/controllers/[Link] (Complete)

const User = require('../models/User');


const mongoose = require('mongoose');

// CREATE - Add new user


const createUser = async (req, res, next) => {
try {
const { unique_id, name, email, contact, membership_fee, validity } = [Link];

if (!unique_id || !name || !email || !contact || membership_fee === undefined) {


if (!unique_id || !name || !email || !contact || membership_fee === undefined) {
return [Link](400).json({
success: false,
message: 'unique_id, name, email, contact, and membership_fee are required'
});
}

const user = await [Link]({


unique_id,
name,
email,
contact,
membership_fee,
validity: validity || 0
});

[Link](201).json({
success: true,
message: 'User created successfully',
data: user
});
} catch (error) {
if ([Link] === 11000) {
const field = [Link]([Link])[0];
return [Link](409).json({
success: false,
message: `${field} already exists`
});
}
if ([Link] === 'ValidationError') {
const errors = [Link]([Link]).map(err => [Link]);
return [Link](400).json({
success: false,
message: [Link](', ')
});
}
next(error);
}
};

// READ - Get all users


const getUsers = async (req, res, next) => {
try {
const users = await [Link]().select('-__v').sort({ createdAt: -1 });
[Link](200).json({
success: true,
count: [Link],
data: users
});
} catch (error) {
next(error);
}
};

// READ - Get one user by ID


const getUserById = async (req, res, next) => {
try {
const { id } = [Link];

if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}
const user = await [Link](id).select('-__v');

if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

[Link](200).json({
success: true,
data: user
});
} catch (error) {
next(error);
}
};

// UPDATE - Update user


const updateUser = async (req, res, next) => {
try {
const { id } = [Link];
const { name, email, contact } = [Link];

if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

const updateData = {};


if (name) [Link] = name;
if (email) [Link] = email;
if (contact) [Link] = contact;

if ([Link](updateData).length === 0) {
return [Link](400).json({
success: false,
message: 'Please provide name, email, or contact to update'
});
}

const user = await [Link](


id,
updateData,
{ new: true, runValidators: true }
).select('-__v');

if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

[Link](200).json({
success: true,
message: 'User updated successfully',
data: user
});
} catch (error) {
if ([Link] === 11000) {
return [Link](409).json({
success: false,
message: 'Email already exists'
});
}
if ([Link] === 'ValidationError') {
const errors = [Link]([Link]).map(err => [Link]);
return [Link](400).json({
success: false,
message: [Link](', ')
});
}
next(error);
}
};

// UPDATE - Renew validity


const renewUser = async (req, res, next) => {
try {
const { id } = [Link];

if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

const user = await [Link](


id,
{ $inc: { validity: 1 } },
{ new: true, runValidators: true }
).select('-__v');

if (!user) {
return [Link](404).json({
success: false,
message: 'User not found'
});
}

[Link](200).json({
success: true,
message: 'Validity renewed successfully',
data: user
});
} catch (error) {
next(error);
}
};

// DELETE - Delete user


const deleteUser = async (req, res, next) => {
try {
const { id } = [Link];

if (![Link](id)) {
return [Link](400).json({
success: false,
message: 'Invalid user ID format'
});
}

const user = await [Link](id);

if (!user) {
return [Link](404).json({
success: false,
success: false,
message: 'User not found'
});
}

[Link](200).json({
success: true,
message: 'User deleted successfully',
data: user
});
} catch (error) {
next(error);
}
};

// Export all functions


[Link] = {
createUser,
getUsers,
getUserById,
updateUser,
renewUser,
deleteUser
};

Step 5: Set Up Express App

File: src/[Link]

const express = require('express');


const userRoutes = require('./routes/users');
const errorHandler = require('./middleware/errorHandler');

const app = express();

// Middleware to parse JSON request body


[Link]([Link]());

// Root endpoint
[Link]('/', (req, res) => {
[Link]({
message: 'Welcome to Randomizer API',
endpoints: {
'POST /api/users': 'Create a new user',
'GET /api/users': 'Get all users',
'GET /api/users/:id': 'Get user by ID',
'PUT /api/users/:id': 'Update user (name, email, contact)',
'PUT /api/users/:id/renew': 'Renew user validity (increment by 1)',
'DELETE /api/users/:id': 'Delete user'
}
});
});

// User routes
[Link]('/api/users', userRoutes);

// Error handler (must be last!)


[Link](errorHandler);

[Link] = app;
Step 6: Create Error Handler

File: src/middleware/[Link]

const errorHandler = (err, req, res, next) => {


[Link]('Error:', err);

// Validation error
if ([Link] === 'ValidationError') {
return [Link](400).json({
success: false,
message: 'Validation error',
error: [Link]
});
}

// Duplicate entry
if ([Link] === 11000) {
return [Link](409).json({
success: false,
message: 'Duplicate entry - this value already exists'
});
}

// Invalid ID
if ([Link] === 'CastError') {
return [Link](400).json({
success: false,
message: 'Invalid ID format'
});
}

// Default error
[Link](500).json({
success: false,
message: 'Something went wrong!',
error: [Link]
});
};

[Link] = errorHandler;

Step 7: Start the Server

File: [Link]

require('dotenv').config(); // Load environment variables


const app = require('./src/app');
const connectDB = require('./src/config/database');

const PORT = [Link] || 3000;

// Connect to database first, then start server


connectDB().then(() => {
[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});
});

Understanding HTTP Status Codes


Code Meaning When to Use

200 OK Successful GET, PUT, DELETE

Successful POST (new resource


201 Created
created)

400 Bad Request Invalid input, missing fields

404 Not Found Resource doesn't exist

409 Conflict Duplicate value (email, unique_id)

500 Server Error Database errors, unexpected errors

Quick Reference: What Each Operation Does

Operation Method Endpoint What It Does

Create POST /api/users Add a new user to database

Read All GET /api/users Get list of all users

Read One GET /api/users/:id Get one user by ID

Update user's name, email, or


Update PUT /api/users/:id
contact

Renew PUT /api/users/:id/renew Add 1 to user's validity

Delete DELETE /api/users/:id Remove user from database

Testing Your API

1. Create a user:

curl -X POST [Link] \


-H "Content-Type: application/json" \
-d '{
"unique_id": "USER001",
"name": "John Doe",
"email": "john@[Link]",
"contact": "1234567890",
"membership_fee": 1000,
"validity": 12
}'

2. Get all users:

curl [Link]

3. Get one user (replace ID with actual ID from step 1):

curl [Link]

4. Update user:
curl -X PUT [Link] \
-H "Content-Type: application/json" \
-d '{
"name": "John Updated",
"email": "[Link]@[Link]"
}'

5. Renew validity:

curl -X PUT [Link]

6. Delete user:

curl -X DELETE [Link]

Summary

What you learned:

1. Model - Defines the data structure (User schema)


2. Routes - Maps URLs to controller functions
3. Controllers - Contains the business logic for each operation
4. CRUD Operations:
Create - [Link]() - Add new user
Read - [Link]() or [Link]() - Get users
Update - [Link]() - Modify user
Delete - [Link]() - Remove user

Key points:

Always validate input before database operations


Always check if user exists before update/delete
Always validate ObjectId format
Always handle errors properly
Use try-catch for all async operations

You now have a working CRUD API.

You might also like