Skip to content

Commit

Permalink
Pagination
Browse files Browse the repository at this point in the history
Small commit due to laptop concerns
  • Loading branch information
Takuya Toyokawa committed Oct 21, 2022
1 parent af3fad0 commit 73b2cb1
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 3 deletions.
31 changes: 29 additions & 2 deletions controllers/bootcamps.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ exports.getBootcamps = asyncHandler(async (req, res, next) => {
const reqQuery = { ...req.query }

// Fiels to exclude
const removeFields = ['select, sort']
const removeFields = ['select', 'sort', 'limit']

// Loop over remove fields and delete them from reqQuery
removeFields.forEach(param => delete reqQuery[param])
Expand Down Expand Up @@ -42,16 +42,43 @@ exports.getBootcamps = asyncHandler(async (req, res, next) => {
query = query.sort('-createdAt')
}

// Pagination
const page = parseInt(req.query.page, 10) || 1
const limit = parseInt(req.query.limit, 10) || 25;
const startIndex = (page - 1) * limit
const endIndex = page * limit
const total = await Bootcamp.countDocuments();

query = query.skip(startIndex).limit(limit)

// Executing Query
const bootcamp = await query

// Pagination result
const pagination = {}

if (endIndex < total) {
pagination.next = {
page: page + 1,
limit
}
}

if (startIndex > 0) {
pagination.prev = {
page: page - 1,
limit
}
}

console.log(queryStr)
res
.status(201)
.json({
success: true,
count: bootcamp.length,
data: bootcamp
pagination,
data: bootcamp,
})
})

Expand Down
3 changes: 3 additions & 0 deletions middleware/async.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// Callsback the controller function
// If promise is not resolved, try catching error

const asyncHandler = fn => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next)

Expand Down
1 change: 0 additions & 1 deletion model/Bootcamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ const mongoose = require('mongoose')
const slugify = require('slugify')
const geocoder = require('../utils/geocoder')


const BootcampSchema = new mongoose.Schema({
name: {
type: String,
Expand Down
38 changes: 38 additions & 0 deletions model/Courses.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const mongoose = require('mongoose')

const CourseSchema = new mongoose.Schema({
title: {
type: String,
trim: true,
required: [true, 'Please add a course title']
},
description: {
type: String,
required: [true, 'Please add a description']
},
weeks: {
type: String,
required: [true, 'Please add number of weeks']
},
tuition: {
type: Number,
required: [true, 'Please add a tuition cost']
},
minimumSkill: {
type: String,
required: [true, 'Please add a minimum skill'],
enum: ['beginner', 'intermediate', 'advanced']
},
createdAt: {
type: Date,
default: Date.now
},
bootcamp: {
type: mongoose.Schema.ObjectId,
// Reference to Schema, not database
ref: 'Bootcamp',
required: true
}
})

module.exports = mongoose.model('Courses', CourseSchema)
5 changes: 5 additions & 0 deletions seeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,21 @@ dotenv.config({ path: './config/config.env' })

// Load models
const Bootcamp = require('./model/Bootcamp')
const Courses = require('./model/Courses')

// Connect to database
mongoose.connect(process.env.MONGO_URI)

// Read JSON files
const bootcamps = JSON.parse(fs.readFileSync(`${__dirname}/_data/bootcamps.json`, 'utf-8'));
const courses = JSON.parse(fs.readFileSync(`${__dirname}/_data/courses.json`, 'utf-8'));


// Import into DB
const importData = async () => {
try {
await Bootcamp.create(bootcamps)
await Courses.create(courses)
console.log('Data imported...'.green.inverse)
} catch (error) {
console.error(error)
Expand All @@ -28,6 +32,7 @@ const importData = async () => {
const deleteData = async () => {
try {
await Bootcamp.deleteMany()
await Courses.deleteMany()
console.log('Data destroyed...'.red.inverse)
} catch (error) {
console.error(error)
Expand Down

0 comments on commit 73b2cb1

Please sign in to comment.