Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Introduction to Project
3.
Lab 1: Setting up the Express worker
4.
Lab 2: Setting up our view engine
5.
Lab 3: Setting up MongoDB
6.
Lab 4: Setting up a Mongoose mapping
7.
Lab 5: Linking the frontend, backend, + MongoDB in project
8.
Lab 6: Displaying short URLs on the frontend of project
9.
Lab 7: Making the redirection work
10.
Conclusion
Last Updated: Mar 27, 2024

Creating a URL Shortner using MongoDB & Node

Author
0 upvote

Introduction

Have you ever considered how you could make a snappy URL shortener for yourself? Like how Twitter abbreviates your connections when you share them? Or on the other hand how bit.ly functions? Sufficiently sure, these are muddled organisations, however, the idea for URL shorteners is basic. We should find out about MongoDB URLand other backend instruments by really assembling this venture in seven stages.

Introduction to Project

We will utilise this free URL shortener study hall from code damn to truly, as truly make and assess our involved venture and see the input.

We will utilize the accompanying advances:

  • Mongoose as the ORM
  • MongoDB as the backend information base
  • Node.js as the backend
  • A straightforward inserted JS document as the frontend
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Lab 1: Setting up the Express worker


It’s a fairly straightforward lab. We have to just create a route /short which should respond appropriately to the browser. This code would let us pass:

// Initialise 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’)
})

Lab 2: Setting up our view engine


We’re utilising a solitary .ejs document, so we should investigate that a bit. Once more, a basic lab since we simply need to change the name of the variable. This ought to complete us:

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’)
})

Lab 3: Setting up MongoDB


In this lab, we’ll associate with MongoDB effectively and embed a record, only for the record. This is the arrangement which ought to get us to the following lab as this is the solution which should get us to the next lab in our project:

app.post(‘/short’, (req, res) => {
const db = mongoose.connection.db
// put the record in ‘test’ collection
db.collection(‘test’).insertOne({ testCompleted: 1 })

res.json({ ok: 1 })

})
// Setup the mongodb connection here
mongoose.connect(‘mongodb://localhost/codedamn’, {
useNewUrlParser: true,
useUnifiedTopology: true
})
mongoose.connection.on(‘open’, () => {
// Wait for mongodb connection until server starts
app.listen(process.env.PUBLIC_PORT, () => {
console.log(‘Server started’)
})
})

Lab 4: Setting up a Mongoose mapping


At long last, we characterise a composition in the models/url.js document for taking care of 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 another task, we update the /short route now.

app.post(‘/short’, async (req, res) => {
// putting the record using the model
const record = new ShortURL({
full: ‘test’
})
await record.save()
res.json({ ok: 1 })
})

Lab 5: Linking the frontend, backend, + MongoDB in project


This is additionally a basic lab. We simply need to refresh the course to separate the URL passed and store it in the information base utilising our outline.
app.use(express.urlencoded({ extended: false }))

app.post(‘/short’, async (req, res) => {
// Take the fullUrl parameter from the req.body
const fullUrl = req.body.fullUrl
console.log(‘URL requested: ‘, fullUrl)

// put and wait for the record to be inserted using the model
const record = new ShortURL({
    full: fullUrl
})

await record.save()

res.redirect('/')

})

Lab 6: Displaying short URLs on the frontend of project


app.get(‘/’, async (req, res) => {
const allData = await ShortURL.find()
res.render(‘index’, { shortUrls: allData })
})

Lab 7: Making the redirection work


app.get(‘/:shortid’, async (req, res) => {
// grab the :shortid parametre
const shortid = req.params.shortid

// do the mongoose call to find the long URL
const rec = await ShortURL.findOne

({ short: shortid })

// if nothing, set status to 404 (res.sendStatus(404))
if (!rec) return res.sendStatus(404)

// if not null, increment the click increase in database
rec.clicks++
await rec.save()

// redirect the user to main/original link
res.redirect(rec.full)

})

Conclusion


You just built a fully working and functional URL shortener by yourself using Express, Node, MongoDB. Give yourself a pat on back!

 

Live masterclass