Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get all company reviews #52 #56

Merged
merged 12 commits into from
Jan 8, 2025
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ npm run dev
The backend server is loading from `http://localhost:3000`

### Environment Variables

One ENV goes inside of the config file inside the server and the other ENV is in the root

```
Expand All @@ -42,4 +41,4 @@ CLERK_SECRET_KEY=clerk_secret_key_here
CLERK_PUBLISHABLE_KEY=clerk_publishable_key_here
```

Front end needs "VITE\_" prefixing all keys
Front end needs "VITE_" prefixing all keys
89 changes: 89 additions & 0 deletions server/controllers/company.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Company from '../models/Company.js'

const companyController = {
//fetches all companies: MIGHT NOT WORK WITHOUT FRONT END?
getAllCompanies: async (req, res, next) => {
try {
const companies = await Company.find({})
Expand All @@ -10,6 +11,94 @@ const companyController = {
next(error)
}
},

//fetches a specfic company (and all of its data):
getCompany: async (req, res, next) => {
try {
const { id } = req.params // Get the company ID from the route parameters
const company = await Company.findById(id).populate('reviews') // Fetch company and populate reviews

if (!company) {
return res.status(404).json({ message: 'Company not found' })
}

res.status(200).json(company)
} catch (error) {
next(error)
}
},

// fetches top 5 companies from DB with the highest review scores:
getBestCompanies: async (req, res, next) => {
try {
const companies = await Company.aggregate([
{
//Joins the reviews collection with the Company collection + stores the matching documents in the 'reviewsData' array.

$lookup: {
from: 'reviews', // Collection that we want data to join
localField: 'reviews', //first field in the current collection
foreignField: '_id', // Other field in the other collection
as: 'reviewsData', // New array field that is storing the joined data
},
},
{
$addFields: {
averageRating: { $avg: '$reviewsData.companyCulture' }, // Calculate the average rating
},
},
{
$sort: { averageRating: -1 }, // Sort by averageRating in descending order
},
{
$limit: 5, // Limits to top 5 companies
},
])

res.status(200).json(companies)
} catch (error) {
next(error)
}
},

//Fetches 5 worst companies, sorted in ascending order using mongoDB
getWorstCompanies: async (req, res, next) => {
try {
const companies = await Company.aggregate([
{
//Joins the reviews collection with the Company collection + stores the matching documents in the 'reviewsData' array.

$lookup: {
from: 'reviews', // Collection that we want data to join
localField: 'reviews', //first field in the current collection
foreignField: '_id', // Other field in the other collection
as: 'reviewsData', // New array field that is storing the joined data
},
},
{
$addFields: {
averageRating: { $avg: '$reviewsData.companyCulture' }, // Calculate the average rating
},
},
{
$sort: { averageRating: 1 }, // Sort by averageRating in ascending order
},
{
$limit: 5, // Limit to bottom 5 companies
},
])

res.status(200).json(companies)
} catch (error) {
next(error)
}
},
}

export default companyController

// considerations:

// do we want to add the ability to limit the number of results that return when a user searches for all companies?

// Should we add query params so that we can filter through specfic companies returned based on specific atributes?
90 changes: 17 additions & 73 deletions server/controllers/reviews.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,22 @@
const cloudinary = require('../middleware/cloudinary')
const Review = require('../models/Reviews')
// import cloudinary from "../middleware/cloudinary";
import Review from "../models/Reviews.js";


const reviewController = {
getProfile: async (req, res) => {
try {
const posts = await Post.find({ user: req.user.id })
res.render('profile.ejs', { posts: posts, user: req.user })
} catch (err) {
console.log(err)
}
},
getFeed: async (req, res) => {
try {
const posts = await Post.find().sort({ createdAt: 'desc' }).lean()
res.render('feed.ejs', { posts: posts })
} catch (err) {
console.log(err)
}
},
getPost: async (req, res) => {
try {
const post = await Post.findById(req.params.id)
res.render('post.ejs', { post: post, user: req.user })
} catch (err) {
console.log(err)
}
},
createPost: async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path)
getAllCompanyReviews: async (req, res, next) => {
try {
//maybe need the company id and review id
//const { companyId } = req.params;
//get all reviews
const reviews = await Review.find({})
console.log(reviews)
//display it in the feed component for the reviews
res.json(reviews); // Send reviews as JSON response
} catch (error) {
next(error)
}
}

await Post.create({
title: req.body.title,
image: result.secure_url,
cloudinaryId: result.public_id,
caption: req.body.caption,
likes: 0,
user: req.user.id,
})
console.log('Post has been added!')
res.redirect('/profile')
} catch (err) {
console.log(err)
}
},
likePost: async (req, res) => {
try {
await Post.findOneAndUpdate(
{ _id: req.params.id },
{
$inc: { likes: 1 },
},
)
console.log('Likes +1')
res.redirect(`/post/${req.params.id}`)
} catch (err) {
console.log(err)
}
},
deletePost: async (req, res) => {
try {
// Find post by id
let post = await Post.findById({ _id: req.params.id })
// Delete image from cloudinary
await cloudinary.uploader.destroy(post.cloudinaryId)
// Delete post from db
await Post.remove({ _id: req.params.id })
console.log('Deleted Post')
res.redirect('/profile')
} catch (err) {
res.redirect('/profile')
}
},
}
}

export default reviewController
5 changes: 4 additions & 1 deletion server/routes/company.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import express from 'express'
const companyRouter = express.Router()
import companyController from '../controllers/company.js'

companyRouter.get('/', companyController.getAllCompanies)
companyRouter.get('/', companyController.getAllCompanies) // GET /company
companyRouter.get('/:id', companyController.getCompany) // GET /company/:id
companyRouter.get('/best', companyController.getBestCompanies) // GET /company/best
companyRouter.get('/worst', companyController.getWorstCompanies) // GET /company/worst

export default companyRouter
20 changes: 6 additions & 14 deletions server/routes/reviews.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import express from 'express'
const reviewRouter = express.Router()
// const upload = require("../middleware/multer");
// const postsController = require("../controllers/posts");
// const { ensureAuth, ensureGuest } = require("../middleware/auth");
import express from 'express';
const reviewRouter = express.Router();
import reviewsController from '../controllers/reviews'

//Post Routes - simplified for now
// router.get("/:id", ensureAuth, postsController.getPost);
//ensure they are logged in aka clerk
reviewRouter.get('/allCompanyReviews', reviewsController.getAllCompanyReviews)

// router.post("/createPost", upload.single("file"), postsController.createPost);

// router.put("/likePost/:id", postsController.likePost);

// router.delete("/deletePost/:id", postsController.deletePost);

// module.exports = router;
export default reviewRouter
export default reviewRouter;