Skip to content

Commit

Permalink
Merge pull request #90 from AVtheking/popular_search
Browse files Browse the repository at this point in the history
implemented popular search feature
  • Loading branch information
AVtheking authored Nov 25, 2023
2 parents 315ff76 + 9f15986 commit 6d14f5a
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 34 deletions.
68 changes: 48 additions & 20 deletions controllers/course_controller.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { Course, Category, User } = require("../models");
const { Course, Category, User, PopularSearch } = require("../models");
const { ErrorHandler } = require("../middlewares/error");
// const redis = require("redis");
const {
Expand All @@ -7,7 +7,7 @@ const {
editReviewSchema,
deleteReviewSchema,
} = require("../utils/validator");
const { count } = require("../models/comment");

//const Enrollment = require('../models/Enrollment');

// const redisClient = redis.createClient();
Expand Down Expand Up @@ -317,6 +317,24 @@ const courseCtrl = {
next(e);
}
},
getPopularSearch: async (req, res, next) => {
try {
const popularSearch = await PopularSearch.find()
.sort({ count: -1 })
.select({ search: 1, _id: 0 })
.limit(5);

res.json({
success: true,
message: "List of popular searches",
data: {
popularSearch,
},
});
} catch (e) {
next(e);
}
},

searchCourses: async (req, res, next) => {
try {
Expand All @@ -325,6 +343,13 @@ const courseCtrl = {
const startIndex = (page - 1) * pageSize;

const searchquery = req.query.coursetitle;
await PopularSearch.findOneAndUpdate(
{
search: searchquery,
},
{ $inc: { count: 1 } },
{ upsert: true }
);
const result = await Course.aggregate([
{
$search: {
Expand Down Expand Up @@ -357,8 +382,11 @@ const courseCtrl = {
},
]);
const searchResults = result[0].searchResults;
const totalCount = result[0].totalCount[0].count;
const totalCount = result[0].totalCount[0]
? result[0].totalCount[0].count
: 0;

// console.log(result[0].totalCount[0].count);
const totalPages = Math.ceil(totalCount / pageSize);

res.json({
Expand All @@ -381,19 +409,19 @@ const courseCtrl = {

const coursesCount = await Course.countDocuments({
isPublished: true,
rating: { $gte: 4.2 },
weightedRating: { $gte: 4.2 },
});

const totalPages = Math.ceil(coursesCount / pageSize);
const popularCourses = await Course.aggregate([
{
$match: {
isPublished: true,
rating: { $gte: 4.2 },
rating: { $gte: 4 },
},
},
{
$sort: { rating: -1 },
$sort: { weightedRating: -1 },
},
{
$skip: startIndex,
Expand Down Expand Up @@ -426,6 +454,7 @@ const courseCtrl = {
thumbnail: 1,
createdAt: 1,
updatedAt: 1,
weightedRating:1,
createdBy: { _id: 1, username: 1, name: 1 },
},
},
Expand Down Expand Up @@ -458,14 +487,14 @@ const courseCtrl = {
return next(new ErrorHandler(400, "Course is not published yet"));
}
const user = req.user;
const courseIdIndex = user.ownedCourse.findIndex((course) =>
course.courseId.equals(courseId)
);
if (courseIdIndex == -1) {
return next(
new ErrorHandler(400, "You have not enrolled in this course")
);
}
// const courseIdIndex = user.ownedCourse.findIndex((course) =>
// course.courseId.equals(courseId)
// );
// if (courseIdIndex == -1) {
// return next(
// new ErrorHandler(400, "You have not enrolled in this course")
// );
// }

const reviewIndex = course.reviews.findIndex((review) =>
review.user.equals(req.user._id)
Expand Down Expand Up @@ -506,7 +535,7 @@ const courseCtrl = {
},
]);
const cummulative_rating = courses[0].avgRating;
console.log(cummulative_rating)
// console.log(cummulative_rating);
const default_rating = 50;
course.weightedRating =
(Rating * totalStudents + default_rating * cummulative_rating) /
Expand All @@ -517,7 +546,6 @@ const courseCtrl = {
rating: userRating,
comment,
};


course.reviews.push(review);
await course.save();
Expand All @@ -527,19 +555,19 @@ const courseCtrl = {
createdBy: course.createdBy,
isPublished: true,
rating: { $exists: true, $ne: null },
}
},
},
{
$group: {
_id: null,
avgRating: { $avg: "$weightedRating" },
},
},
])
console.log(educator_courses[0].avgRating)
]);
console.log(educator_courses[0].avgRating);
user.educator_rating = educator_courses[0].avgRating;
if (user.educator_rating >= 2.5) {
user.is_certified_educator=true
user.is_certified_educator = true;
}
await user.save();

Expand Down
4 changes: 3 additions & 1 deletion controllers/user_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ const userCtrl = {
const path = user.profileimg;
user.profileimg = null;
await user.save();
fs.unlinkSync("public" + "/" + path);
if (path != null) {
fs.unlinkSync("public" + "/" + path);
}
res.json({
success: true,
message: "Profile picture deleted successfully",
Expand Down
4 changes: 2 additions & 2 deletions models/course.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ const courseSchema = new mongoose.Schema(
},
reviews: [reviewSchema],
weightedRating: {
type: String,

type: Number,
default: 0,
},
},
{
Expand Down
1 change: 1 addition & 0 deletions models/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ module.exports.Category = require("./category");
module.exports.Message = require("./message");
module.exports.Review = require("./review");
module.exports.Comment = require("./comment");
module.exports.PopularSearch = require("./popular_search");
16 changes: 16 additions & 0 deletions models/popular_search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require("mongoose");

const popularSearchSchema = new mongoose.Schema({
search: {
type: String,
required: true,
trim: true,
unique: true,
},
count: {
type: Number,
default: 1,
},
});
const PopularSearch = mongoose.model("PopularSearch", popularSearchSchema);
module.exports = PopularSearch;
7 changes: 6 additions & 1 deletion routes/courseRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@ courseRouter.get(
courseCtrl.getCoursesByCategory
);
courseRouter.get("/getCourseById/:courseId", auth, courseCtrl.getCourseByid);
courseRouter.get("/video/:courseId/lecture/:lectureId", auth,videoCtrl.streamVideo);
courseRouter.get(
"/video/:courseId/lecture/:lectureId",
auth,
videoCtrl.streamVideo
);
courseRouter.get("/getCategoriesName", auth, courseCtrl.getCategoriesName);
courseRouter.get("/getCategoriesData", auth, courseCtrl.getCategoriesData);
courseRouter.get("/get-reviews/:courseId", auth, courseCtrl.getReviews);
courseRouter.get("/get-popular-course", auth, courseCtrl.getPopularCourses);
courseRouter.get("/popular-search", courseCtrl.getPopularSearch);

courseRouter.get("/search-course", courseCtrl.searchCourses);
courseRouter.get("/get-popular-course", courseCtrl.getPopularCourses);
Expand Down
33 changes: 23 additions & 10 deletions routes/userRouter.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const express = require('express');
const userRouter = express.Router();
const express = require("express");
const userRouter = express.Router();

const { userCtrl } = require('../controllers');
const { uploadImage, auth } = require('../middlewares');
const { userCtrl } = require("../controllers");
const { uploadImage, auth } = require("../middlewares");

userRouter.get("/get-cart", auth, userCtrl.getCoursesInCart);
userRouter.get("/get-wishlist", auth, userCtrl.getWishlist);
userRouter.get("/search-user", userCtrl.searchUser);
userRouter.get("/search-user", userCtrl.searchUser);
userRouter.get("/completed-course", auth, userCtrl.getCompletedCourse);
userRouter.get("/get-ownedCourses", auth, userCtrl.getOwnedCourses);
userRouter.get("/get-user/:userId", userCtrl.getUserById);
Expand All @@ -16,11 +16,24 @@ userRouter.post("/add-wishlist/:courseId", auth, userCtrl.addToWishlist);
// userRouter.post("/add-to-oc/:courseId/lecture/:lectureId", auth, userCtrl.addToOC);
// userRouter.post("/add-lecture-oc/:courseId/lecture/:lectureId", auth, userCtrl.addlecture);

userRouter.delete("/delete-cart/:courseId", auth, userCtrl.deleteCourseFromCart);
userRouter.delete(
"/delete-cart/:courseId",
auth,
userCtrl.deleteCourseFromCart
);
userRouter.delete("/delete-profileImg", auth, userCtrl.deleteProfilePicture);
userRouter.delete("/delete-wishlist/:courseId", auth, userCtrl.deleteCourseFromWishlist);
userRouter.delete(
"/delete-wishlist/:courseId",
auth,
userCtrl.deleteCourseFromWishlist
);

userRouter.patch('/update-profileImg', auth, uploadImage, userCtrl.uploadProfilePicture);
userRouter.patch('/update-profile', auth, userCtrl.updateProfile);
userRouter.patch(
"/update-profileImg",
auth,
uploadImage,
userCtrl.uploadProfilePicture
);
userRouter.patch("/update-profile", auth, userCtrl.updateProfile);

module.exports = userRouter;
module.exports = userRouter;

0 comments on commit 6d14f5a

Please sign in to comment.