Skip to content

Homework Solutions for Classes 52-55 #758

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
.env
.vscode
.vscode
.DS_Store
74 changes: 74 additions & 0 deletions controllers/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
const Comment = require("../models/Comment");
const Post = require("../models/Post");

module.exports = {
createComment: async (req, res) => {
try {
await Comment.create({
comment: req.body.comment,
likes: 0,
post: req.params.id,
user: req.user.id,
userName: req.user.userName,
});
console.log("Comment has been added!");
res.redirect("/post/"+req.params.id);
} catch (err) {
console.log(err);
}
},

likeComment: async (req, res) => {
try {
const comment = await Comment.findById(req.params.commentId);

if (comment) {
// Check if the user has already liked the comment
const userIndex = comment.likedBy.indexOf(req.user.id);

if (userIndex > -1) {
// User has liked the comment; remove the like
comment.likedBy.splice(userIndex, 1);
comment.likes -= 1;
} else {
// User has not liked the comment; add the like
comment.likedBy.push(req.user.id);
comment.likes += 1;
}

await comment.save();
console.log("Like toggled");
res.redirect(`/post/${comment.post}`);
} else {
console.log("Comment not found");
res.redirect('/someErrorPage');
}
} catch (err) {
console.log(err);
res.redirect('/someErrorPage');
}
},

deleteComment: async (req, res) => {
try {
// Find the comment by ID
const comment = await Comment.findById(req.params.commentId);

// Check if the user is the owner of the comment or the post
if (comment.user.equals(req.user.id) || req.user.isAdmin) { // Add your admin check here
// Delete the comment
await Comment.findByIdAndRemove(req.params.commentId);
console.log("Deleted Comment");
} else {
console.log("User not authorized");
return res.redirect("/post/" + req.params.postId);
}

res.redirect("/post/" + req.params.postId);
} catch (err) {
console.log(err);
res.redirect("/post/" + req.params.postId);
}
},

};
38 changes: 28 additions & 10 deletions controllers/posts.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const cloudinary = require("../middleware/cloudinary");
const Post = require("../models/Post");
const Comment = require("../models/Comment");

module.exports = {
getProfile: async (req, res) => {
Expand All @@ -20,8 +21,9 @@ module.exports = {
},
getPost: async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.render("post.ejs", { post: post, user: req.user });
const post = await Post.findById(req.params.id).populate('user').lean();
const comments = await Comment.find({post: req.params.id}).sort({ createdAt: "desc" }).lean();
res.render("post.ejs", { post: post, user: req.user , comments: comments});
} catch (err) {
console.log(err);
}
Expand All @@ -38,6 +40,7 @@ module.exports = {
caption: req.body.caption,
likes: 0,
user: req.user.id,
userName: req.user.userName,
});
console.log("Post has been added!");
res.redirect("/profile");
Expand All @@ -47,18 +50,33 @@ module.exports = {
},
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}`);
const postId = req.params.id;
const userId = req.user.id;

const post = await Post.findById(postId);

// Check if the user has already liked the post
if (post.likedBy.includes(userId)) {
// If already liked, remove the like
await Post.findByIdAndUpdate(postId, {
$pull: { likedBy: userId },
$inc: { likes: -1 }
});
} else {
// Otherwise, add the like
await Post.findByIdAndUpdate(postId, {
$push: { likedBy: userId },
$inc: { likes: 1 }
});
}

res.redirect(`/post/${postId}`);
} catch (err) {
console.log(err);
res.redirect(`/post/${req.params.id}`);
}
},

deletePost: async (req, res) => {
try {
// Find post by id
Expand Down
35 changes: 35 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const mongoose = require("mongoose");

const CommentSchema = new mongoose.Schema({
comment: {
type: String,
required: true,
},
likes: {
type: Number,
required: true,
},
likedBy: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }], // Array of user IDs who liked the comment
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
userName: {
type: String, // Add this line to store the user's name
required: true, // Optional: you can choose to make it required
},
createdAt: {
type: Date,
default: Date.now,
},
});

module.exports = mongoose.model("Comment", CommentSchema);
4 changes: 4 additions & 0 deletions models/Post.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,14 @@ const PostSchema = new mongoose.Schema({
type: Number,
required: true,
},
likedBy: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }], // Array of user IDs who liked the post

user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},


createdAt: {
type: Date,
default: Date.now,
Expand Down
Binary file modified public/.DS_Store
Binary file not shown.
Loading