Section 31 – Lesson 408 – Complete 2020 Web Development Bootcamp

Lesson 408 – Letting Users Submit Secrets

The next step it to refactor the code to allow users to submit secrets which are then shown on the secrets page of the website.

To do this, you have to create an app.get(“/submit”) route –

app.get("/submit", function(req, res) {
	if (req.isAuthenticated()) {
		res.render("submit");
	} else {
	}
});

You then have to create a new app.post route(“/submit”) like this –

app.post("/submit", function(req, res) {
	const submittedSecret = req.body.secret;

	User.findById(req.user.id, function(err, foundUser){
		if (err) {
			console.log(err);
		} else {
			if (foundUser) {
				foundUser.secret = submittedSecret;
				foundUser.save(function() {
					res.redirect("/secrets");
				});
			}
		}
	});
});

The const userSchema also has to be refactored to include a secret like this –

const userSchema = new mongoose.Schema ({
	email: String,
	password: String,
	googleId: String,
	secret: String
});

The app.get(“/secrets”) route has to be updated like this –

app.get("/secrets", function(req, res) {
	User.find({secret: {$ne: null}}, function(err, foundUsers) {
		if(err) {
			console.log(err);
		} else {
			if (foundUsers) {
				res.render("secrets", {usersWithSecrets: foundUsers});
			}
		}
	});
});

Next the secrets.ejs file has to be updated so that it loops through all of the stored secrets and displays them to the user. This is the updated code –

<%- include('partials/header') %>

<div class="jumbotron text-center">
  <div class="container">
    <i class="fas fa-key fa-6x"></i>
    <h1 class="display-3">You've Discovered My Secret!</h1>
    

   <% usersWithSecrets.forEach(function(user) { %>

    	<p class="secret-text"> <%=user.secret%> </p>

   <% }) %>

    
    <hr>
    
    <a class="btn btn-light btn-lg" href="/logout" role="button">Log Out</a>
    <a class="btn btn-dark btn-lg" href="/submit" role="button">Submit a Secret</a>
  </div>
</div>

<%- include('partials/footer') %>