Loading

Quipoin Menu

Learn • Practice • Grow

express-js / MongoDB + Mongoose with Express
tutorial

MongoDB + Mongoose with Express

Imagine you have a box of LEGO bricks. You can build anything, add new pieces anytime, and the structure can change as you play. MongoDB is like that it's flexible and doesn't force you to follow a strict blueprint. Mongoose is like a set of instructions that helps you build consistently while still keeping the flexibility.

What is MongoDB?

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents called BSON (Binary JSON). Instead of tables with rows and columns, MongoDB uses collections and documents.
  • Collection Like a table in SQL, it's a group of related documents.
  • Document Like a row, but flexible. Each document can have different fields.

What is Mongoose?

Mongoose is an ODM (Object Document Mapper) for MongoDB and Node.js. It provides a schema-based solution to model your data, with built-in validation, query building, and middleware.

Installing Mongoose
npm install mongoose

Connecting to MongoDB with Mongoose
const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('Connection error:', err);
});

Defining a Schema and Model
A schema defines the structure of your documents. A model is a compiled version of the schema that lets you interact with the database.
// Define a schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18 },
createdAt: { type: Date, default: Date.now }
});

// Create a model
const User = mongoose.model('User', userSchema);

CRUD Operations with Mongoose

Create (Insert) a User
app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});

Read (Find) Users
// Get all users
app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
res.status(500).json({ error: error.message });
}
});

// Get user by ID
app.get('/users/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});

Update a User
app.put('/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).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(400).json({ error: error.message });
}
});

Delete a User
app.delete('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});

Mongoose Schema Options
  • required Field must be provided
  • default Default value if not provided
  • unique Ensure no duplicate values
  • min/max Validation for numbers
  • enum Value must be in specified array
  • validate Custom validation function

Two Minute Drill
  • MongoDB stores data in flexible documents (BSON format).
  • Mongoose is an ODM that provides structure and validation.
  • Define a schema, then create a model from it.
  • Use model methods like save(), find(), findById(), findByIdAndUpdate(), findByIdAndDelete().
  • Always handle errors with try/catch in async routes.
  • Mongoose is perfect for Express apps that need a flexible, schema-less database.

Need more clarification?

Drop us an email at career@quipoinfotech.com