Today's lab session focused on how to build a MiniPost REST microservice with an API by connecting to a MongoDB database to collect data and render it to the browser.
Lab 3 focuses on how to:
-
Conceptualise a REST API development for the CRUD operations:
- Create data
- Read data
- Update data
- Delete data
-
Deploy a MongoDB instance on the MongoDB Atlas
-
Create a MiniPost REST API using Node.js
The following image demonstrates the MiniPost microservice architecture.
You will need to watch the next video on how to install and run a Node.js app.
Take your time, make sure you double-check the code and debug your code as you go.
- Firstly, watch the following video.
READ THIS FIRST:
Due to a recent Node.js update, the following script (used in the video) will no longer work:
app.listen(3000, () => { console.log('Server is up and running...'); });To fix this issue, please remove the callback or use the new Promise-based syntax.
The correct options are:
app.listen(3000);or
app.listen(3000) .then(() => console.log('Server is up and running...')) .catch(err => console.error('Failed to start server:', err));
You should run this tutorial on your personal computer ✅
- Here, you will find the commands and scripts that I created in this video. Assuming that you already installed NodeJS on your personal computer, and you are already in your project folder, you can initialise a NodeJS application using the following script.
$ npm initnpm is the node package manager that gives us access to the online repository of Node.
- For this tutorial, we need to install the
expresspackage, thenodemontool, themongoosedriver to connect to the MongoDB cluster, thebody-parserto parse body data as JSON objects, and thedotenvthat allows you to separate secrets from your source code.
$ npm install express nodemon mongoose body-parser dotenv You can install all packages at the same time using one command.
- Make sure you edit the
package.jsonand adapt thescriptskey to the following value (as shown in the video).
...
"scripts": {
"start":"nodemon app.js"
}- You will need to create a new MongoDB collection using the MongoDB atlas. Watch the video on how to connect and deploy your first MongoDB cluster.
Link to connect to the MongoDB cluster.
- This is an example of a data instance of the mongoose model that we use in this tutorial. The data is in JSON format.
{
"user":"Stelios",
"title":"Hi!",
"text":"Hi, I am Stelioa and this is my first post!",
"hashtag":"#VideoGaming",
"location":"London",
"url":"https://stelios.com",
"date":"2022-01-23T10:10:10"
}- The next script is the code used in the
app.jsfile.
const express = require('express')
const app = express()
const mongoose =require('mongoose')
require('dotenv/config')
const bodyParser = require('body-parser')
const postsRoute = require('./routes/posts')
app.use(bodyParser.json())
app.use('/posts',postsRoute)
app.get('/', (req,res) =>{
res.send('Homepage')
})
mongoose.connect(process.env.DB_CONNECTOR).then(()=>{
console.log('Your mongoDB connector is on...')
})
app.listen(3000, ()=>{
console.log('Server is up and running...')
})- We created a new model called
Post.jsinside the newmodelsfolder.
const mongoose = require('mongoose')
const PostSchema = mongoose.Schema({
user:{
type:String,
required:true
},
title:{
type:String,
required:true
},
text:{
type:String,
required:true
},
hashtag:{
type:String,
required:true
},
location:{
type:String,
required:true
},
url:{
type:String,
required:true
},
date:{
type:Date,
default:Date.now
}
})
module.exports = mongoose.model('posts',PostSchema)- We created the
posts.jsfile inside a newroutesfolder.
const express =require('express')
const router = express.Router()
const Post = require('../models/Post')
// POST (Create data)
router.post('/',async(req,res)=>{
//console.log(req.body)
const postData = new Post({
user:req.body.user,
title:req.body.title,
text:req.body.text,
hashtag:req.body.hashtag,
location:req.body.location,
url:req.body.url
})
// try to insert...
try{
const postToSave = await postData.save()
res.send(postToSave)
}catch(err){
res.send({message:err})
}
})
// GET 1 (Read all)
router.get('/', async(req,res) =>{
try{
const getPosts = await Post.find().limit(10)
res.send(getPosts)
}catch(err){
res.send({message:err})
}
})
// GET 2 (Read by ID)
router.get('/:postId', async(req,res) =>{
try{
const getPostById = await Post.findById(req.params.postId)
res.send(getPostById)
}catch(err){
res.send({message:err})
}
})
// PATCH (Update)
router.patch('/:postId', async(req,res) =>{
try{
const updatePostById = await Post.updateOne(
{_id:req.params.postId},
{$set:{
user:req.body.user,
title:req.body.title,
text:req.body.text,
hashtag:req.body.hashtag,
location:req.body.location,
url:req.body.url
}
})
res.send(updatePostById)
}catch(err){
res.send({message:err})
}
})
// DELETE (Delete)
router.delete('/:postId',async(req,res)=>{
try{
const deletePostById = await Post.deleteOne({_id:req.params.postId})
res.send(deletePostById)
}catch(err){
res.send({message:err})
}
})
module.exports = router- You need to run the
npm startto start the server.
$ npm start- Make sure you create a couple of extra routes and familiarise yourself with the NodeJS code.
🏁 Well done! You completed lab 3!
Now create your own data schema and implement the CRUD operations in Node.js! 👏

