Let us learn about MongoDB, Mongoose, Node, and other tech by building a simple URL shortener project.
Have you ever wondered how you could create a quick URL shortener for yourself? Like how twitter shortens your links when you share them? Or how bit.ly works?
Sure enough, these are complicated companies, but the concept for URL shorteners is simple. Let's learn about MongoDB and other backend tools by actually building this project in 7 steps.
We will be using this free URL shortener classroom from codedamn to really, like really create and evaluate our hands-on project and see the feedback.
We will be using the following technologies:
The link of this lab is here
It's a fairly straightforward lab. We have to just create a route /short which should respond appropriately. This code would let us pass:
// Initialize express server on PORT 1337
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World! - from codedamn')
})
app.get('/short', (req, res) => {
res.send('Hello from short')
})
app.listen(process.env.PUBLIC_PORT, () => {
console.log('Server started')
})
The link of this lab is here
We're using a single .ejs file, so let's explore that a little. Again, a very simple lab because we just have to change the name of the variable. This should get us done:
const express = require('express')
const app = express()
app.set('view engine', 'ejs')
app.get('/', (req, res) => {
res.render('index', { myVariable: 'My name is John!' })
})
app.listen(process.env.PUBLIC_PORT, () => {
console.log('Server started')
})
The link of this lab is here
In this lab, we'll connect to MongoDB correctly and insert a record, just for the record
This is the solution which should get us to the next lab:
app.post('/short', (req, res) => {
const db = mongoose.connection.db
// insert the record in 'test' collection
db.collection('test').insertOne({ testCompleted: 1 })
res.json({ ok: 1 })
})
// Setup your mongodb connection here
mongoose.connect('mongodb://localhost/codedamn', {
useNewUrlParser: true,
useUnifiedTopology: true
})
mongoose.connection.on('open', () => {
// Wait for mongodb connection before server starts
app.listen(process.env.PUBLIC_PORT, () => {
console.log('Server started')
})
})
The link of this lab is here
Finally, we define a schema in the models/url.js file for proper handling with Mongoose, and here's the code for that:
const mongoose = require('mongoose')
const shortId = require('shortid')
const shortUrlSchema = new mongoose.Schema({
full: {
type: String,
required: true
},
short: {
type: String,
required: true,
default: shortId.generate
},
clicks: {
type: Number,
required: true,
default: 0
}
})
module.exports = mongoose.model('ShortUrl', shortUrlSchema)
Also, as part of the challenge, we update the `/short` route now.
app.post('/short', async (req, res) => {
// insert the record using the model
const record = new ShortURL({
full: 'test'
})
await record.save()
res.json({ ok: 1 })
})
This is also a simple lab. We just have to update the route to extract the URL passed and store it in the database using our schema.
app.use(express.urlencoded({ extended: false }))
app.post('/short', async (req, res) => {
// Grab the fullUrl parameter from the req.body
const fullUrl = req.body.fullUrl
console.log('URL requested: ', fullUrl)
// insert and wait for the record to be inserted using the model
const record = new ShortURL({
full: fullUrl
})
await record.save()
res.redirect('/')
})
Now, we display the URL set on our website using the .ejs variables passed.
app.get('/', async (req, res) => {
const allData = await ShortURL.find()
res.render('index', { shortUrls: allData })
})
Finally, we link up the redirection scheme using dynamic express routes and correct status codes.
app.get('/:shortid', async (req, res) => {
// grab the :shortid param
const shortid = req.params.shortid
// perform the mongoose call to find the long URL
const rec = await ShortURL.findOne({ short: shortid })
// if null, set status to 404 (res.sendStatus(404))
if (!rec) return res.sendStatus(404)
// if not null, increment the click count in database
rec.clicks++
await rec.save()
// redirect the user to original link
res.redirect(rec.full)
})
And we can call it a day! You just built a fully working URL shortener by yourself using Express + Node + MongoDB. Give yourself a pat on back!
The final source code is available on GitHub
If you have any feedback on this article or codedamn classrooms, feel free to reach out to me on twitter and let's discuss :)
Also published at https://dev.to/mehulmpt/create-a-url-shortener-project-using-mongodb-node-but-hands-on-1ai2