Simplifying Node.js, Express.js, and MongoDB Integration for API Development
In my last story, I wrote about how to create an API using Node.js and Express.js. In that story I am storing data inside an array, today I want to share how to store the data in the database instead. See my last story.
Step 1: Connect to a database
In a real-world scenario, you would want to store the data in a database instead of an array. You can use a variety of databases with Node.js, such as MongoDB, MySQL, or PostgreSQL. For this example, I’ll use MongoDB with the Mongoose library.
First, download and install the Mongo DB Community Server here. Then, install the Mongoose library by running the following command:
$ npm install mongoose
Next, add the following code to the app.js
file to connect to a MongoDB database:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/node-express-api', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
Test the code by running the server node app.js
. You will see this in the terminal.
Step 2: Define a Mongoose model
A Mongoose model defines the structure of the data that will be stored in the MongoDB database. Add the following code to the app.js
file to define a Mongoose model for the items:
const itemSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
const Item = mongoose.model('Item', itemSchema);
Step 3: Modify the routes to use the database
Finally, modify the routes to use the MongoDB database instead of the array. Replace the existing code for the /items
and /items/:id
routes with the following code:
app.get('/items', async (req, res) => {
const items = await Item.find();
res.send(items);
});
app.get('/items/:id', async (req, res) => {
const item = await Item.findById(req.params.id);
if (!item) return res.status(404).send('Item not found');
res.send(item);
});
In the code above, the Item.find()
method is used to retrieve all items from the database, and the Item.findById()
method is used to retrieve a specific item by its _id
.
Step 4: Add a POST route
Now let’s add a POST
route to allow clients to create new items. Add the following code to the app.js
file:
app.post('/items', async (req, res) => {
let item = new Item({ name: req.body.name });
item = await item.save();
res.send(item);
});
Step 5: Add a PUT route
Now let’s add a PUT
route to allow clients to update existing items. Add the following code to the app.js
file:
app.put('/items/:id', async (req, res) => {
const item = await Item.findByIdAndUpdate(req.params.id, { name: req.body.name });
if (!item) return res.status(404).send('Item not found');
res.send(item);
});
In the code above, the Item.findByIdAndUpdate()
method is used to find an item by its _id
and update its name.
Step 6: Add a DELETE route
Finally, let’s add a DELETE
route to allow clients to delete existing items. Add the following code to the app.js
file:
app.delete('/items/:id', async (req, res) => {
const item = await Item.findByIdAndRemove(req.params.id);
if (!item) return res.status(404).send('Item not found');
res.send(item);
});
In the code above, the Item.findByIdAndRemove()
the method is used to find an item by its _id
and remove it from the database.
Final code,
// Database: MongoDB
const mongoose = require('mongoose');
mongoose.set('strictQuery', false);
mongoose.connect('mongodb://127.0.0.1:27017/node-express-api', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
// Models
const itemSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
const Item = mongoose.model('Item', itemSchema);
// Express
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server started on port 3000');
});
// Routes
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/items', async (req, res) => {
const items = await Item.find();
res.send(items);
});
app.get('/items/:id', async (req, res) => {
const item = await Item.findById(req.params.id);
if (!item) return res.status(404).send('Item not found');
res.send(item);
});
app.post('/items', async (req, res) => {
let item = new Item({ name: req.body.name });
item = await item.save();
res.send(item);
});
app.put('/items/:id', async (req, res) => {
const item = await Item.findByIdAndUpdate(req.params.id, { name: req.body.name }, { new: true });
if (!item) return res.status(404).send('Item not found');
res.send(item);
});
app.delete('/items/:id', async (req, res) => {
const item = await Item.findByIdAndRemove(req.params.id);
if (!item) return res.status(404).send('Item not found');
res.send(item);
});
Step 7: Testing
After completing the code, you need to test the API. Usually, I’m using postman for testing the endpoint and creating the documentation. I’ll conduct the manual test. The test scenario is
- Add data 2 data
After adding 2 data, you can check on the MongoDB database using GUI
- Get all data
- Get data by data-id
- Update 1 data by the data-id
After updating the item, get the item to check
Check through GUI
- Delete 1 data by its id
Deleting the data will return the deleted data.
Check
Get all data to see if the data is deleted.
Conclusion
By following the steps outlined in this story, you were able to create an API and integrate it with a Database, in this case, MongoDB. So, what do you think? I love to hear your comment.