Mongoose and Express CRUD Operations Highlights Reel
# Mongoose and Express CRUD Operations Highlights Reel
## 1. CREATE (Insert) Operation
```javascript
// Define the schema
const bookSchema = new mongoose.Schema({
title: String,
author: { type: mongoose.Schema.Types.ObjectId, ref: 'Author' },
publishedYear: Number
});
// Create the model
const Book = mongoose.model('Book', bookSchema);
// Express route for creating a new book
app.post('/api/books', async (req, res) => {
const book = new Book({
title: req.body.title,
author: req.body.authorId,
publishedYear: req.body.publishedYear
});
Key Points:
- Mongoose schema defines the structure of the document
- `new Book(...)` creates a new document instance
- `book.save()` inserts the document into the MongoDB collection
### Read One
```javascript
app.get('/api/books/:id', async (req, res) => {
try {
const book = await Book.findById(req.params.id).populate('author');
if (!book) return res.status(404).json({ message: 'Book not found' });
res.json(book);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
```
Key Points:
- `Book.find()` retrieves all documents
- `Book.findById()` retrieves a single document by its ID
- `.populate('author')` replaces the author ID with the full author document
## 3. UPDATE Operation
```javascript
app.patch('/api/books/:id', async (req, res) => {
try {
const book = await Book.findById(req.params.id);
if (!book) return res.status(404).json({ message: 'Book not found' });
if (req.body.title) book.title = req.body.title;
if (req.body.authorId) book.author = req.body.authorId;
if (req.body.publishedYear) book.publishedYear = req.body.publishedYear;
Key Points:
- `Book.findById()` first retrieves the document
- Update only the fields that are provided in the request
- `book.save()` saves the updated document back to the database
Key Points:
- `Book.findById()` first retrieves the document
- `book.remove()` deletes the document from the database
## Summary
- Mongoose provides a schema-based solution to model your application data
- Express routes handle HTTP requests and delegate database operations to Mongoose
- Mongoose methods like `save()`, `find()`, `findById()`, and `remove()` map to CRUD operations
- Async/await is used to handle asynchronous database operations
- Error handling is crucial in each operation to provide proper feedback
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (