MongoDB + Mongoose with Express
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. **Mongoose** is an ODM (Object Document Mapper) that provides a schema-based solution to model your application data. Together, they make working with MongoDB in Express a breeze.
Why MongoDB + Mongoose?
- Schema-less but with structure: Mongoose adds schema validation while keeping MongoDB's flexibility.
- Built-in validation: Define rules for your data.
- Middleware (hooks): Run code before/after database operations.
- Population: Easy way to reference documents in other collections.
Think of Mongoose as a helpful assistant that makes sure your data is properly formatted before it goes into MongoDB, and nicely packaged when it comes out.
Installation
npm install mongooseConnecting to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp', { 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.
<!-- models/User.js -->const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, age: { type: Number, min: 0 }, createdAt: { type: Date, default: Date.now }, isActive: { type: Boolean, default: true }});
<!-- Create the model -->const User = mongoose.model('User', userSchema);
module.exports = User;CRUD Operations with Mongoose
Create (POST)
app.post('/users', async (req, res) => { try { const user = new User(req.body); const savedUser = await user.save(); res.status(201).json(savedUser); } catch (err) { res.status(400).json({ error: err.message }); }});Read (GET)
<!-- Get all users -->app.get('/users', async (req, res) => { try { const users = await User.find(); res.json(users); } catch (err) { res.status(500).json({ error: err.message }); }});
<!-- Get single 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 (err) { res.status(500).json({ error: err.message }); }});Update (PUT)
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 (err) { res.status(400).json({ error: err.message }); }});Delete (DELETE)
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.status(204).send(); } catch (err) { res.status(500).json({ error: err.message }); }});Two Minute Drill
- MongoDB is a NoSQL database that stores data as JSON-like documents.
- Mongoose is an ODM that provides schema validation and modeling for MongoDB.
- Define schemas to structure your data and models to interact with the database.
- Mongoose provides methods like `find()`, `findById()`, `save()`, `findByIdAndUpdate()` for CRUD.
- Always use `try/catch` with async/await for error handling.
Need more clarification?
Drop us an email at career@quipoinfotech.com
