The next Product College class starts January 2018. Apply Now

Associate Posts and Comments with User

Associate Posts and Comments with User

August 22, 2017

Alright next step! Its time to allow people to take responsibility for the silly things they are posting on our Reddit clone. We are going to create user accounts so folks can securely signup and login using a username and password.

  1. Create a post
  2. Show all posts
  3. Show one post
  4. Comment on posts
  5. Create subreddits
  6. Sign up and Login
  7. Associate posts and comments with their author
    1. Add author attribute to comments and posts
    2. Save the user as the author of posts
    3. Remove the ability to comment on one's own posts
    4. Display the author's username on posts and comments
  8. Make comments on comments
  9. Vote a post up
  10. Sort posts by # of votes

Add the author Attribute to Comment and Post Models

Let's add an author attribute to both the comment.js and the post.js files and let's make it required:

, author         : { type: Schema.Types.ObjectId, ref: 'User', required: true }

Save the Current User as the Author of Posts and Comments

Now we can update the posts controller to save the current user as the author when we create a post.

User.findById(req.user._id).exec(function (err, user) {
  var post = new Post(req.params.tourId); (err, post) {
    res.redirect('/posts/'+ post._id)

Test that this is working in your project.

Now can you do this same pattern for the comments controller for when someone creates a comment?

Displaying the Author

Now populate the author in posts and display their username on every post wherever it appears.

Extra Challenges:

  1. Can you make an author's username a link that displays that users's profile at /users/:username?
  2. Can you do the same for comments?


If you have feedback on this tutorial or find any mistakes, please open issues on the GitHub Repository or comment below.

Summer academy

An iOS Development Summer Course

Design, code and launch your own app. Locations across the USA and Asia

Find your location

Product College

A computer science college

Graduate into a successful career as a founder or software engineer.

Learn more