Project: Job Board
In this project you build FreshersHub, a job board for freshers. Employers post jobs with a city and a salary range in lakh rupees per annum (LPA). Candidates filter jobs by city, type, skill and minimum salary, apply with a PDF resume, and follow each application's status. Employers see a dashboard that counts applicants by status, download resumes and move candidates along. It is the last build of the course, so it reuses every pattern you know and adds three new ones: two kinds of users, a validated query string, and private files that two different people may open.
What you should know first: the whole course, especially Project: Notes App and Project: Recipe Sharing Site, whose skeleton and ForbiddenError we reuse. Versions used: Node.js 26 LTS, Express 5.3.0, Mongoose 9.12.1 on MongoDB 9.0, Zod 4.6.7, multer 2.5.0, Vue 3.5, Vue Router 5.5.1, Pinia 4.1.0 and Vite 8.3.8.
What you will build
Picture the placement cell notice board at a college in Kochi. Companies pin up openings, students read them and drop their resumes in a box, and only the company that pinned an opening may open the resumes for it. FreshersHub puts that board online:
| Method and path | Purpose | Access |
|---|---|---|
GET /api/jobs?city=&type=&skill=&minSalary=&page= | Search open jobs, 10 per page | Public |
GET /api/jobs/:id | One job | Public |
POST /api/jobs, PATCH /api/jobs/:id | Post a job, open or close it | Employer (own jobs) |
POST /api/jobs/:id/applications | Apply with a PDF and a cover note | Candidate, once per job |
GET /api/applications/mine | My applications and their status | Candidate |
GET /api/jobs/:id/applications, PATCH /api/applications/:id | Applicants for my job, change a status | Employer (own jobs) |
GET /api/applications/:id/resume | Download a resume | The candidate or the job's employer |
GET /api/employer/jobs | Dashboard with counts by status | Employer |
Step 1: Start from the skeleton
Copy NoteNest's server/ and client/, delete the notes files, and add ForbiddenError (403) to errors.js as in the recipe project. Rename images.js to files.js with saveFile(buffer, extension) and removeFile(filename): the same random-name logic, now for PDFs. The finished tree:
freshershub/
├── client/src/
│ ├── api/ client.js, auth.js, jobs.js
│ ├── components/ ApplyForm.vue
│ ├── router/ index.js with meta.role
│ ├── stores/ auth.js, jobs.js
│ ├── utils/ money.js (₹ and LPA)
│ └── views/ JobsView, JobDetailView, MyApplicationsView, DashboardView,
│ PostJobView, ApplicantsView, LoginView, SignupView, NotFoundView
└── server/src/
├── middleware/ auth (requireAuth + requireRole), upload (PDF), validate (body + query), ...
├── models/ User.js (role), Job.js, Application.js
└── routes/ auth.js, jobs.js, applications.js, employer.jsStep 2: Two roles in one account
Every account is either an employer or a candidate, chosen at sign-up. The User model gains role: { type: String, enum: ROLES, required: true } and an optional company. Only employers may name a company, and they must. Zod 4's discriminated union picks the right schema by looking at one field, here role:
// server/src/routes/auth.js
// The role decides which other fields are allowed: only employers name a company.
const signupSchema = z.discriminatedUnion(
'role',
[
z.object({ ...account, role: z.literal('candidate') }),
z.object({
...account,
role: z.literal('employer'),
company: z.string({ error: 'Company is required' }).trim().min(2, 'Company is required').max(80),
}),
],
{ error: 'Role must be employer or candidate' },
)account holds the name, email and password rules from Authentication with JWT & Cookies. Two real sign-up attempts, an employer without a company and someone choosing "role":"admin":
{"error":{"code":"VALIDATION_ERROR","message":"Company is required"}}
{"error":{"code":"VALIDATION_ERROR","message":"Role must be employer or candidate"}}Nobody can make themselves an admin, because the schema lists the only two roles. The login cookie's token now carries the role, jwt.sign({ sub: user.id, role: user.role }, ...), and requireAuth copies it to req.role. A tiny middleware then guards routes by role:
// server/src/middleware/auth.js (new)
// Use after requireAuth: requireRole('employer') lets only employers through.
export function requireRole(role) {
return (req, res, next) => {
if (req.role !== role) throw new ForbiddenError(`Only ${role}s can do this`)
next()
}
}The token is signed, so a user cannot edit their role inside it. The trade-off: if you ever let people change roles, an old token keeps the old role for up to seven days. Then you would read the role from the database on each request instead.
Step 3: Job posts with a salary in LPA
Freshers compare offers in LPA, so store salaries the way people talk: salaryMin: 3.5 means ₹3,50,000 a year. The Job model has title, company (copied from the employer's account, never from the request), city from a fixed list of ten (Bengaluru, Pune, Kochi, Remote and others), type (full-time or internship), salaryMin, salaryMax, up to ten lowercase skills, description, status (open or closed) and employer. An index on { status: 1, city: 1, salaryMax: -1 } serves the main search.
Two salary rules are easy to get wrong, so Zod checks both. Steps of 0.5 LPA avoid prices like 3.27, and the maximum may not be below the minimum:
// server/src/routes/jobs.js
// Salary in LPA, in steps of 0.5: 3, 3.5, 4...
const lpa = z
.number({ error: 'Salary must be a number in LPA' })
.min(1, 'Salary must be at least 1 LPA')
.max(100, 'Salary can be at most 100 LPA')
.refine((n) => Number.isInteger(n * 2), 'Use steps of 0.5 LPA')
const jobSchema = z
.object({
city: z.enum(CITIES, { error: 'Choose a city from the list' }),
salaryMin: lpa,
salaryMax: lpa,
// title, type, skills and description as usual
})
.refine((job) => job.salaryMax >= job.salaryMin, {
message: 'Maximum salary cannot be below the minimum',
path: ['salaryMax'],
})Number.isInteger(n * 2) is true for 3 and 3.5 but false for 4.2. Ananya sent salaryMin: 6, salaryMax: 4.2, and the test saw both problems in one message: Use steps of 0.5 LPA. Maximum salary cannot be below the minimum. POST /api/jobs runs requireAuth, requireRole('employer'), validateBody(jobSchema), so a candidate gets 403 before any of this.
Step 4: Filters in the URL, checked by Zod
In NoteNest and RasoiShare the routes checked each query value by hand. Here there are five filters, so describe them once with Zod. Everything in a URL is text, so z.coerce.number() turns "4" into 4, and a missing page becomes 1:
// Every filter is optional. Numbers arrive as text in a URL, so z.coerce turns them into numbers.
const jobQuery = z.object({
city: z.enum(CITIES, { error: 'Unknown city' }).optional(),
type: z.enum(JOB_TYPES, { error: 'Unknown job type' }).optional(),
skill: z.string().trim().toLowerCase().max(30, 'A skill can have at most 30 characters').optional(),
minSalary: z.coerce.number({ error: 'minSalary must be a number' }).min(0).max(100).optional(),
page: z.coerce.number().int('Page must be a whole number').min(1, 'Page starts at 1').max(50, 'Page can be at most 50').default(1),
})Our first validateQuery copied validateBody and wrote the clean result back with req.query = result.data. Every search then failed with a 500. In Express 5, req.query is a getter with no setter, and a three-line test app showed the error:
500 {"error":"TypeError: Cannot set property query of #<IncomingMessage> which has only a getter"}So the clean copy goes into its own property:
// server/src/middleware/validate.js (new)
// Checks the query string. Express 5 makes req.query read-only, so the clean copy goes in req.filters.
export function validateQuery(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.query)
if (!result.success) throw new ValidationError(messages(result.error))
req.filters = result.data
next()
}
}The route builds the filter from req.filters only. "Pays at least 4 LPA" means the top of the range reaches 4, so filter.salaryMax = mongoose.trusted({ $gte: minSalary }), and status: 'open' is always added. We seeded two employers (Ananya's Pixel Pune Labs and Farhan's Kochi Cloud Works), six jobs (one closed) and two candidates, then searched (our run used port 3562):
--- city=Pune
[
'Node.js intern | Pune | 2-2.5',
'Junior Vue developer | Pune | 3.5-5'
]
--- minSalary=4
[
'Cloud support associate | Kochi | 3.5-4.5',
'QA engineer (fresher) | Kochi | 3-4',
'MEVN trainee | Remote | 4-6',
'Junior Vue developer | Pune | 3.5-5'
]
--- skill=vue&type=internship
[]
--- city=Delhi
{"error":{"code":"VALIDATION_ERROR","message":"Unknown city. Too small: expected number to be >=1"}}The closed Bengaluru job never appears. The last request was ?city=Delhi&page=0. It showed Zod's default message, which suits developers, not users, so we added the messages you see in the schema above: page=0 now says Page starts at 1.
Step 5: Apply with a PDF resume
The upload middleware from File Uploads & Images changes in three places. The file is a PDF, the limit is 1 MB, and the form carries one text field, the cover note:
// server/src/middleware/upload.js
export const uploadResume = multer({
storage: multer.memoryStorage(),
// One file and one text field (the cover note). Anything more is refused.
limits: { fileSize: MAX_RESUME_BYTES, files: 1, fields: 1, fieldSize: 2000 },
fileFilter(req, file, cb) {
if (file.mimetype === 'application/pdf') return cb(null, true)
cb(new ValidationError('Upload your resume as a PDF'))
},
}).single('resume')
// Every PDF starts with the bytes "%PDF-". The browser's mimetype is only a claim.
export function isPdf(buffer) {
return buffer.length > 5 && buffer.toString('latin1', 0, 5) === '%PDF-'
}multer fills req.body.coverNote from the form, and the route checks it with Zod's safeParse (at most 1,000 characters). An Application stores job, candidate, coverNote, resume: { filename, size } and status, one of applied, shortlisted, rejected or hired. A unique index on { job: 1, candidate: 1 } allows one application per job, the same idea as RasoiShare's likes. The route saves the file, then creates the document, and deletes the file again if the insert fails:
// uploadResume runs before requireRole: answering 403 while the file is still arriving resets the connection.
router.post('/:id/applications', requireAuth, uploadResume, requireRole('candidate'), async (req, res) => {
// ...find the open job, check the cover note, check isPdf(req.file.buffer)
const filename = await saveFile(req.file.buffer, '.pdf')
try {
const application = await Application.create({ /* job, candidate, coverNote, resume */ })
res.status(201).json({ application })
} catch (err) {
await removeFile(filename) // do not keep a file nobody points to
if (err.code === 11000) throw new ConflictError('You have already applied for this job')
throw err
}
})The comment on the first line records a real failure. We first put requireRole('candidate') before uploadResume. The test "employers cannot apply" then failed with Error: read ECONNRESET instead of a 403. The server answered while the PDF was still arriving and closed the connection with the upload unread, so the client saw a broken connection. A browser can show that as "Cannot reach the server". With multer first, the body is read (at most 1 MB, in memory, never saved) and the 403 arrives in our JSON shape. Four real attempts: Rohan's application, the same again, a text file named .pdf, and Ananya trying to apply:
{"application":{"id":"6afb0388eed201e989babe17","job":"6afb0326c823bce63fb04aa5","candidate":"6afb0326c823bce63fb04aa3","coverNote":"I built a notes app with Vue and Express in my final year.","status":"applied","createdAt":"2026-11-16T13:22:16.066Z","updatedAt":"2026-11-16T13:22:16.066Z","resume":{"size":628}}}
{"error":{"code":"CONFLICT","message":"You have already applied for this job"}}
{"error":{"code":"VALIDATION_ERROR","message":"That file is not a real PDF"}}
{"error":{"code":"FORBIDDEN","message":"Only candidates can do this"}}Step 6: Who may open a resume
A resume holds a phone number, an address and a college record. Two people may see it: the candidate who sent it and the employer who owns the job. Everyone else gets 404, as if it did not exist:
// server/src/routes/applications.js
async function findVisibleApplication(id, req) {
const application = mongoose.isObjectIdOrHexString(id) ? await Application.findById(id) : null
if (application) {
if (req.role === 'candidate' && application.candidate.equals(req.userId)) return application
if (req.role === 'employer' && (await Job.exists({ _id: application.job, employer: req.userId }))) {
return application
}
}
throw new NotFoundError('Application not found')
}
// GET /api/applications/:id/resume: download, never shown inline
router.get('/:id/resume', async (req, res) => {
const application = await findVisibleApplication(req.params.id, req)
res.attachment(`resume-${application.id}.pdf`) // Content-Disposition: attachment
res.sendFile(application.resume.filename, {
root: config.uploadDir,
cacheControl: false,
headers: { 'Content-Type': 'application/pdf', 'Cache-Control': 'private, no-store' },
})
})res.attachment() tells the browser to save the file instead of opening it inside our site, so a crafted document cannot pose as one of our pages. no-store keeps it out of shared computers' caches, which matters in a college lab or a cyber cafe. Ananya's real download:
HTTP/1.1 200 OK X-Content-Type-Options: nosniff Content-Type: application/pdf Content-Disposition: attachment; filename=resume-6afb0388eed201e989babe17.pdf Cache-Control: private, no-store
Farhan, another employer, and Isha, another candidate, both got 404 in the tests.
Step 7: Status changes and the dashboard
PATCH /api/applications/:id takes { "status": "shortlisted" } (checked with z.enum) and uses the same findVisibleApplication, behind requireRole('employer'). When Rohan tried to mark himself hired, he got Only employers can do this.
The dashboard needs, for every job, how many applications sit in each status. One query per job would be slow for an employer with 40 jobs. An aggregation pipeline groups and counts in one trip (see The Aggregation Pipeline):
// server/src/routes/employer.js, GET /api/employer/jobs
const jobs = await Job.find({ employer: req.userId }).sort({ createdAt: -1 }).limit(100)
// One aggregation instead of one query per job: group by (job, status) and count.
const rows = await Application.aggregate([
{ $match: { job: { $in: jobs.map((j) => j._id) } } },
{ $group: { _id: { job: '$job', status: '$status' }, count: { $sum: 1 } } },
])The route then fills a { applied, shortlisted, rejected, hired } object for each job, with zeros where no row exists. Notice that $in inside $match needed no mongoose.trusted(): sanitizeFilter guards query filters such as find(), not aggregation pipelines. That makes a rule for pipelines: put only values your code produced in them, such as these ids, never raw input. After Ananya shortlisted Rohan, her dashboard data was:
Node.js intern open {"applied":0,"shortlisted":0,"rejected":0,"hired":0}
MEVN trainee open {"applied":0,"shortlisted":0,"rejected":0,"hired":0}
Junior Vue developer open {"applied":0,"shortlisted":1,"rejected":0,"hired":0}Step 8: The Vue side
Rupees need care. client/src/utils/money.js keeps all formatting in one place, using Intl.NumberFormat('en-IN') for Indian digit grouping (lakhs and crores):
// client/src/utils/money.js
const rupees = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 })
export function formatLpa(min, max) {
return min === max ? `₹${min} LPA` : `₹${min} to ${max} LPA`
}
export function yearly(lpa) {
return rupees.format(lpa * 100000) // yearly(3.5) -> "₹3,50,000"
}
export function monthly(lpa) {
return rupees.format((lpa * 100000) / 12) // before tax
}Its Vitest test checks ₹3.5 to 5 LPA, ₹3,50,000, ₹12,00,000 and ₹29,167, and passed. The job page shows all three, because a fresher deciding between offers in Pune and Kochi thinks in monthly take-home.
Routes carry the role they need, and the guard from Forms, Login & Protected Routes gains one line:
// client/src/router/index.js
// { path: '/dashboard', ..., meta: { requiresAuth: true, role: 'employer' } }
const homeFor = (user) => (user.role === 'employer' ? { name: 'dashboard' } : { name: 'jobs' })
router.beforeEach(async (to) => {
const auth = useAuthStore()
await auth.ensureChecked()
if (to.meta.requiresAuth && !auth.isLoggedIn) {
return { name: 'login', query: { redirect: to.fullPath } }
}
// A candidate typing /dashboard goes to their own home page. The API still checks the role.
if (to.meta.role && auth.user.role !== to.meta.role) return homeFor(auth.user)
if (to.meta.guestOnly && auth.isLoggedIn) return homeFor(auth.user)
})JobsView treats the URL as the only source of truth, exactly like NoteNest's search: a computed reads route.query, a watch calls the Pinia jobs store's fetchJobs, and the filter form is a draft that becomes router.push({ query }) only when the user presses Search. ApplyForm.vue checks type and size for a quick message, then sends one FormData with coverNote and resume; apiRequest already leaves the multipart Content-Type alone. Resume downloads are plain links to /api/applications/:id/resume: same origin, so the cookie goes with them.
In headless Chrome, on the production build, we opened /?city=Pune and saw two jobs. We chose the skill "vue" and pressed Search, and the address became /?city=Pune&skill=vue with one job left. Rohan then logged in from /login?redirect=/dashboard and was sent to / instead, and his "My applications" table read Junior Vue developer, Pixel Pune Labs | ₹3.5 to 5 LPA | shortlisted. Ananya landed on /dashboard and saw the counts above.
Step 9: Tests and release
server/test/jobs.test.js signs up two employers and two candidates with a signUp(app, name, company) helper, and uses a real 628-byte PDF and a text file named fake.pdf as fixtures:
▶ jobs and filters ✔ only employers can post, and the salary range must make sense (53.9693ms) ✔ filters by city, type, skill and minimum salary from the query string (134.4505ms) ✔ jobs and filters (19503.4923ms) ▶ applications ✔ a candidate applies once with a real PDF (179.9947ms) ✔ refuses a text file that claims to be a PDF (36.3234ms) ✔ employers cannot apply (27.0685ms) ✔ the resume goes only to the candidate and the job owner, as a download (138.0009ms) ✔ the employer dashboard counts applications by status (194.9494ms) ✔ applications (580.0356ms) ℹ tests 7 ℹ suites 2 ℹ pass 7 ℹ fail 0
On the client, the money and jobs-store tests passed 3 of 3. Deploy as in Deploying a MEVN App, and add these points for a site that stores resumes:
- Resumes are personal data. India's Digital Personal Data Protection Act, 2023 expects you to keep only what you need, protect it and delete it when asked, so plan a delete-my-account flow and an expiry for old applications.
UPLOAD_DIR(for example/var/lib/freshershub/resumes) must be readable only by the service user, and its backups must be protected as carefully as the database's.client_max_body_size 2min Nginx is enough for a 1 MB PDF plus the form.- Never log cover notes or file contents, only ids.
Try the filter rules
Type a query string as it would appear after /? in the address bar. The page checks it like jobQuery, then filters open jobs like the server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FreshersHub filters</title>
<script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-width: 38rem; }
input { width: 100%; padding: 4px; }
.error { color: #b00020; }
</style>
</head>
<body>
<div id="app">
<h1>Jobs for freshers</h1>
<label>Query string <input v-model="query" placeholder="city=Pune&minSalary=4"></label>
<p>Try: <code>city=Kochi</code>, <code>minSalary=4.5</code>, <code>skill=VUE&type=internship</code>, <code>city=Delhi&page=0</code></p>
<p v-if="errors.length" class="error">400: {{ errors.join(". ") }}</p>
<ul v-else>
<li v-for="j in results" :key="j.title">
<strong>{{ j.title }}</strong>, {{ j.city }}: {{ lpa(j) }} ({{ yearly(j.min) }} to {{ yearly(j.max) }} a year)
</li>
<li v-if="results.length === 0">No open jobs match these filters.</li>
</ul>
</div>
<script>
const { createApp, ref, computed } = Vue;
const CITIES = ["Bengaluru", "Chennai", "Gurugram", "Hyderabad", "Jaipur", "Kochi", "Mumbai", "Noida", "Pune", "Remote"];
const jobs = [
{ title: "Junior Vue developer", city: "Pune", type: "full-time", min: 3.5, max: 5, skills: ["vue", "javascript"], open: true },
{ title: "Node.js intern", city: "Pune", type: "internship", min: 2, max: 2.5, skills: ["node", "mongodb"], open: true },
{ title: "MEVN trainee", city: "Remote", type: "full-time", min: 4, max: 6, skills: ["vue", "node"], open: true },
{ title: "QA engineer (fresher)", city: "Kochi", type: "full-time", min: 3, max: 4, skills: ["testing"], open: true },
{ title: "Front-end developer", city: "Bengaluru", type: "full-time", min: 5, max: 7, skills: ["vue", "css"], open: false }
];
const rupees = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
createApp({
setup() {
const query = ref("city=Pune");
const parsed = computed(() => {
const p = new URLSearchParams(query.value.replace(/^\?/, ""));
const errors = [], f = {};
if (p.has("city")) CITIES.includes(p.get("city")) ? (f.city = p.get("city")) : errors.push("Unknown city");
if (p.has("type")) ["full-time", "internship"].includes(p.get("type")) ? (f.type = p.get("type")) : errors.push("Unknown job type");
if (p.has("skill")) f.skill = p.get("skill").trim().toLowerCase();
if (p.has("minSalary")) {
const n = Number(p.get("minSalary"));
Number.isNaN(n) || n < 0 || n > 100 ? errors.push("minSalary must be a number from 0 to 100") : (f.minSalary = n);
}
if (p.has("page") && !(Number.isInteger(Number(p.get("page"))) && Number(p.get("page")) >= 1)) errors.push("Page starts at 1");
return { errors, f };
});
const errors = computed(() => parsed.value.errors);
const results = computed(() => {
const f = parsed.value.f;
return jobs.filter((j) => j.open
&& (!f.city || j.city === f.city)
&& (!f.type || j.type === f.type)
&& (!f.skill || j.skills.includes(f.skill))
&& (f.minSalary === undefined || j.max >= f.minSalary));
});
const lpa = (j) => (j.min === j.max ? `₹${j.min} LPA` : `₹${j.min} to ${j.max} LPA`);
const yearly = (n) => rupees.format(n * 100000);
return { query, errors, results, lpa, yearly };
}
}).mount("#app");
</script>
</body>
</html>minSalary=4.5 keeps the Remote and Pune jobs whose top reaches 4.5. The Bengaluru job never shows, because it is closed.
Common mistakes
- Trusting the role the client sends. The role comes from the signed token (set at sign-up by a schema with two allowed values), never from a request body or a hidden form field.
- Assigning to
req.queryin Express 5. It throws; store validated values in your own property such asreq.filters. - Refusing an upload before reading it. An early 403 or 401 on a multipart route can reach the client as a reset connection. Let multer read the small, limited body, then refuse.
- Serving resumes inline or with a public cache. Use
Content-Disposition: attachment,Cache-Control: private, no-storeand an access check for exactly two people. - Showing salaries as
350000. UseIntl.NumberFormat('en-IN')so readers see₹3,50,000.
Interview questions
1. How would you implement roles such as employer and candidate in an Express API?
Store the role on the user, fix the allowed values with an enum in both Zod and Mongoose, and put it in the signed JWT. A requireRole('employer') middleware after requireAuth refuses other roles with 403. Ownership is still checked per record, because being an employer does not make every job yours.
2. Why validate query strings, and what does z.coerce.number() do?
Query values are user input like any body, and every value arrives as a string. z.coerce.number() converts the string with Number() before checking it, so "4" becomes 4 and "lots" fails. Validating once in middleware gives clear 400 messages and a clean req.filters object for the route.
3. Why serve uploaded PDFs with Content-Disposition: attachment?
It makes the browser download the file instead of rendering it on your origin, which reduces the risk from crafted documents. With X-Content-Type-Options: nosniff, the correct Content-Type and an access check, users get the file without the site treating it as a page.
4. How do you count applications per job and status efficiently in MongoDB?
Use one aggregation: $match the employer's job ids, then $group by { job, status } with $sum: 1. The application fills in zeros for missing combinations. This replaces one query per job with a single round trip.
Key points
- FreshersHub reuses the skeleton: one error shape, Zod, Argon2 and the JWT cookie, multer checks, rate limits, Pinia, Vue Router, tests and deployment.
- Roles are chosen at sign-up through a Zod discriminated union, carried in the signed token and enforced with
requireRole. - Salaries are stored as LPA numbers in steps of 0.5, checked with
refine, and shown withIntl.NumberFormat('en-IN'). - Filters live in the URL;
validateQuerycoerces and checks them and stores the result inreq.filters, because Express 5'sreq.queryis read-only. - Applications need a real PDF (
%PDF-), at most 1 MB, and a unique{ job, candidate }index; multer runs before the role check. - Resumes download only for the candidate and the job's employer, as attachments with
no-store. - The dashboard counts by status with one
$groupaggregation built only from server-side ids.
Exercise
Let a candidate withdraw an application while its status is still applied. Add DELETE /api/applications/:id for candidates only: it must find the candidate's own application, refuse with a 409 if the status is no longer applied, delete the document and its PDF, and answer 204. Add a "Withdraw" button on MyApplicationsView for applications in the applied state. Write two API tests: withdrawing works and the candidate can then apply again, and withdrawing a shortlisted application returns 409.
Show solution
// server/src/routes/applications.js
router.delete('/:id', requireRole('candidate'), async (req, res) => {
const application = await findVisibleApplication(req.params.id, req)
if (application.status !== 'applied') {
throw new ConflictError('This application is already being reviewed')
}
await application.deleteOne()
await removeFile(application.resume.filename)
res.status(204).end()
})findVisibleApplication already returns only the candidate's own application, so someone else's id gets a 404. Deleting the document also frees the unique { job, candidate } pair, which is why applying again works. Delete the file after the document, so a failed delete never leaves a record pointing at a missing PDF. On the client, call apiRequest('/applications/' + id, { method: 'DELETE' }) and remove the row; in the 409 test, shortlist the application as the employer first.
Quick Quiz
1. An employer signs up without a company name. What happens?
The role field chooses which object schema applies.
2. Why does validateQuery store its result in req.filters?
Our first version failed with "Cannot set property query ... which has only a getter".
3. What does minSalary=4 return?
The filter is salaryMax with $gte, plus status open.
4. Who can download Rohan's resume for the Junior Vue developer job?
findVisibleApplication allows the candidate and the job's own employer; everyone else gets 404.
Learn MEVN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
