Skip to content

Comments via embedded documents within Post schema #7

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 5 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
21 changes: 21 additions & 0 deletions controllers/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,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 Down Expand Up @@ -73,4 +74,24 @@ module.exports = {
res.redirect("/profile");
}
},
commentPost: async (req, res) => {
console.log(req.body.comment);
try {
await Post.findOneAndUpdate(
{ _id: req.params.id },
{ $push: {
comments: {
message: req.body.comment,
userName: req.user.userName,
user: req.user.id,
}}
}
);
console.log("Comment added");
res.redirect(`/post/${req.params.id}`);
} catch (err) {
console.log(err);
res.redirect(`/post/${req.params.id}`);
}
}
};
34 changes: 34 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const mongoose = require("mongoose");

const CommentSchema = new mongoose.Schema({
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
},
message: {
type: String,
required: true
},
likes: {
type: Number,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
userName: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now,
},
replies: {
type: [this],
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is where you can recursively add Comment replies as arrays of Comments (who will then each have their own Comment replies array), by referencing "this".

required: false
}
});

module.exports = mongoose.model("Comment", CommentSchema);
6 changes: 6 additions & 0 deletions models/Post.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const mongoose = require("mongoose");
const Comments = require("./Comment");

const PostSchema = new mongoose.Schema({
title: {
Expand All @@ -25,6 +26,11 @@ const PostSchema = new mongoose.Schema({
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
userName: {
type: String,
required: true
},
comments: [Comments.schema],
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where you can add Comments Schema as an embedded document to the Post Schema, to save yourself from additional queries after first querying for your Post.

You automatically get the Comments associated with that Post, just by querying the Post.

createdAt: {
type: Date,
default: Date.now,
Expand Down
2 changes: 0 additions & 2 deletions models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const UserSchema = new mongoose.Schema({
});

// Password hash middleware.

UserSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
Expand All @@ -29,7 +28,6 @@ UserSchema.pre("save", function save(next) {
});

// Helper method for validating user's password.

UserSchema.methods.comparePassword = function comparePassword(
candidatePassword,
cb
Expand Down
29 changes: 29 additions & 0 deletions public/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* Overlay the username above the sibling image*/
.username-overlay {
transform: translateY(-100%);
text-decoration: none;
text-decoration-style: revert;
color: white;
font-size: 1.5rem;
}
.comments {
margin: 2rem 0;
}
.comment {
margin: 1.5rem 0;
background-color: #FEFEFE;
border-radius: 5px;
padding: 0.5rem;
}
.comment-text {
font-size: 1rem;
margin: 0;
}
.comment-username {
font-size: 0.75rem;
font-weight: bold;
color: #343434;
}
.comment-input-label {
font-size: 0.75rem
}
2 changes: 2 additions & 0 deletions routes/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ const { ensureAuth, ensureGuest } = require("../middleware/auth");
router.get("/", homeController.getIndex);
router.get("/profile", ensureAuth, postsController.getProfile);
router.get("/feed", ensureAuth, postsController.getFeed);

router.get("/login", authController.getLogin);
router.post("/login", authController.postLogin);
router.get("/logout", authController.logout);

router.get("/signup", authController.getSignup);
router.post("/signup", authController.postSignup);

Expand Down
6 changes: 3 additions & 3 deletions routes/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ const { ensureAuth, ensureGuest } = require("../middleware/auth");

//Post Routes - simplified for now
router.get("/:id", ensureAuth, postsController.getPost);

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

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

// Comments are only ever accessed via Posts as embedded documents,
// so it makes sense for the comments to be part of the Post routes.
router.post("/comment/:id", ensureAuth, postsController.commentPost);
router.delete("/deletePost/:id", postsController.deletePost);

module.exports = router;
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,5 @@ app.use("/post", postRoutes);

//Server Running
app.listen(process.env.PORT, () => {
console.log("Server is running, you better catch it!");
console.log(`Server is running at PORT ${process.env.PORT}, you better catch it!`);
});
10 changes: 6 additions & 4 deletions views/feed.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
<div class="container">
<div class="row justify-content-center mt-5">
<ul class="row list-unstyled">
<% for(var i=0; i<posts.length; i++) {%>

<% for (const post of posts) { %>
<li class="col-6 justify-content-between mt-5">
<a href="/post/<%= posts[i]._id%>">
<img class="img-fluid" src="<%= posts[i].image%>">
<a href="/post/<%= post._id%>">
<img class="img-fluid" src="<%= post.image%>">
<h1 class="username-overlay"><%=post.userName%></h1>
</a>
</li>
<% } %>
</ul>
</ul>
</div>
</div>
<%- include('partials/footer') -%>
43 changes: 37 additions & 6 deletions views/post.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@
<form
class="col-1"
action="/post/likePost/<%= post.id %>?_method=PUT"
method="POST"
>
<button class="btn btn-primary fa fa-heart" type="submit"></button>
method="POST">
<button class="btn btn-danger fa fa-heart" type="submit"></button>
</form>
<h3 class="col-3">Likes: <%= post.likes %></h3>
<%if(post.user == user.id){ %>
<%if(post.user === user.id){ %>
<form
action="/post/deletePost/<%= post.id %>?_method=DELETE"
method="POST"
Expand All @@ -24,13 +23,45 @@
<%}%>
</div>
</div>
<div class="col-3 mt-5">

<section class="col-3 mt-5 comments-section">
<p><%= post.caption %></p>
</div>

<form action="/post/comment/<%= post.id %>" method="POST">
<div class="form-group">
<label for="comment" class="comment-input-label">Comment</label>
<textarea
class="form-control"
id="comment"
name="comment"
rows="3"
></textarea>
</div>
<button type="submit" class="btn btn-primary">add comment</button>
</form>

<div class="comments">
<% post.comments.forEach(comment => { %>
<div class="comment">
<p class="comment-text"><%= comment.message %></p>
<span class="comment-username"><%= comment.userName %></span>

<% for (const reply of comment.replies) { %>
<div class="comment">
<p class="comment-text"><%= reply.message %></p>
<span class="comment-username"><%= reply.userName %></span>
</div>
<% } %>
</div>
<% }) %>
</div>
</section>

<div class="col-6 mt-5">
<a class="btn btn-primary" href="/profile">Return to Profile</a>
<a class="btn btn-primary" href="/feed">Return to Feed</a>
</div>

</div>
</div>

Expand Down
15 changes: 10 additions & 5 deletions views/profile.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,23 @@
</div>
<div class="mb-3">
<label for="imgUpload" class="form-label">Image</label>
<input type="file" class="form-control" id="imageUpload" name="file">
<input
type="file"
class="form-control"
id="imageUpload"
name="file"
accept="image/gif, image/jpeg, image/png, video/mp4"
>
</div>
<button type="submit" class="btn btn-primary" value="Upload">Submit</button>
</form>
</div>
</div>
<div class="col-6">
<ul class="row list-unstyled">
<div class="row justify-content-center mt-5">
<a class="btn btn-primary" href="/feed">Return to Feed</a>
</div>
<% for(var i=0; i<posts.length; i++) {%>
<li class="col-6 justify-content-between mt-5">
<a href="/post/<%= posts[i]._id%>">
Expand All @@ -36,11 +45,7 @@
</li>
<% } %>
</ul>
<div class="row justify-content-center mt-5">
<a class="btn btn-primary" href="/feed">Return to Feed</a>
</div>
</div>
</div>
</div>
</div>
<%- include('partials/footer') -%>