Hey there, fellow code wranglers! Ready to dive into the world of MongoDB API integration? You're in for a treat. We'll be building a robust API that'll make your data dance to your tune. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get our project off the ground:
mkdir mongodb-api-integration cd mongodb-api-integration npm init -y npm install express mongodb mongoose dotenv
Alright, time to make that connection! Create a .env
file and add your MongoDB URI:
MONGODB_URI=your_mongodb_uri_here
Now, let's establish that connection:
const mongoose = require('mongoose'); require('dotenv').config(); mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected!')) .catch(err => console.error('MongoDB connection error:', err));
Let's create a simple schema for, say, a book collection:
const mongoose = require('mongoose'); const bookSchema = new mongoose.Schema({ title: String, author: String, year: Number }); module.exports = mongoose.model('Book', bookSchema);
Time to give our API some muscles! Here's a quick implementation of CRUD operations:
const Book = require('./models/book'); // Create exports.createBook = async (req, res) => { try { const book = new Book(req.body); await book.save(); res.status(201).json(book); } catch (error) { res.status(400).json({ error: error.message }); } }; // Read exports.getBooks = async (req, res) => { try { const books = await Book.find(); res.json(books); } catch (error) { res.status(500).json({ error: error.message }); } }; // Update exports.updateBook = async (req, res) => { try { const book = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.json(book); } catch (error) { res.status(400).json({ error: error.message }); } }; // Delete exports.deleteBook = async (req, res) => { try { await Book.findByIdAndDelete(req.params.id); res.json({ message: 'Book deleted successfully' }); } catch (error) { res.status(400).json({ error: error.message }); } };
Let's wire up those CRUD operations to some endpoints:
const express = require('express'); const router = express.Router(); const bookController = require('./controllers/bookController'); router.post('/books', bookController.createBook); router.get('/books', bookController.getBooks); router.put('/books/:id', bookController.updateBook); router.delete('/books/:id', bookController.deleteBook); module.exports = router;
We've got some basic error handling in our CRUD operations, but let's add a global error handler:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });
For validation, consider using a library like Joi or leverage Mongoose's built-in validation.
Fire up Postman or curl and start hitting those endpoints! Here's a quick example:
curl -X POST -H "Content-Type: application/json" -d '{"title":"1984","author":"George Orwell","year":1949}' http://localhost:3000/api/books
To keep things speedy:
Index frequently queried fields:
bookSchema.index({ title: 1, author: 1 });
Use projection to limit returned fields:
Book.find({}, 'title author');
Don't forget to add authentication and authorization! Consider using JWT tokens and implement HTTPS in production.
Ready to show your API to the world? Consider platforms like Heroku or AWS. Don't forget to set your environment variables and ensure your database is properly secured.
And there you have it! You've just built a MongoDB API integration that's ready to take on the world. Remember, this is just the beginning - there's always room to grow and optimize. Keep exploring, keep coding, and most importantly, keep having fun with it!
Happy coding, you MongoDB maestro!