Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"axios": "^1.6.7",
"cors": "^2.8.5",
"express": "^4.18.2",
"mongoose": "^8.2.0"
}
Example: Implementation to setup the backend for the above the project.
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
const connectDB = require('./db');
const Userdb = require('./models');
const port = 3001;
// Connect to the database
connectDB();
// Middleware to parse JSON bodies
app.use(express.json());
// Enable CORS
app.use(cors());
// Home route
app.get("/", (req, res) => {
res.send("<h1>Home page of a Job portal </h1>")
});
// Create a new job
app.post("/api/jobs", async (req, res) => {
const { title,
company,
location,
description, salary } = req.body;
try {
const newJob = new Userdb({
title,
company,
location,
description,
salary
});
await newJob.save();
res.status(201).json(newJob);
} catch (error) {
console.error('Error creating job:', error);
res.status(500).json(
{ message: 'Server Error' }
);
}
});
// Get all jobs
app.get("/api/jobs", async (req, res) => {
try {
const jobs = await Userdb.find();
res.json(jobs);
} catch (error) {
console.error('Error getting jobs:', error);
res.status(500).json(
{ message: 'Server Error' }
);
}
});
// Start the server
app.listen(port, () => {
console.log(
`Server is started at port no ${port}`);
});
// db.js
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect('YOURS URI', {
});
console.log('Database is connected');
} catch (err) {
console.error('Error connecting to the database:', err);
process.exit(1);
}
};
module.exports = connectDB;
//model.js
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: String,
description: String,
salary: {
type: Number,
required: true
}
});
const Userdb = mongoose.model('userdb', schema);
module.exports = Userdb;
Steps to run the backend Application
node server.js
Job Search Portal with MERN Stack
In this tutorial, we’ll guide you through the process of creating a Job Search Portal using the MERN Stack – MongoDB for storing job and user data, Express.js for building web applications, React.js for creating user interfaces, and Node.js for server-side programming.
Output Preview: