Commit 63358bc2 authored by Kristian Freeman's avatar Kristian Freeman

Answer key - mongo-express

parent e7b070c1
// Import the file ./utils/connection, setting
// it to the variable connect.
const connect = require("./utils/connection");
const bodyParser = require("body-parser");
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
// Import body-parser, setting it to bodyParser.
const port = process.env.PORT || 8080;
// Import express.
const app = express();
// Import mongoose.
app.use(morgan("combined"));
// Import morgan.
app.use(bodyParser.urlencoded({ extended: false }));
// Set the variable port to process.env.PORT or 8080.
app.use(bodyParser.json());
// Set the variable app to the result of calling the express function.
const { userRouter } = require("./routes/user");
// Call app.use, passing in the morgan function, which you should call
// with the string argument "combined". This sets up a nice logger
// middleware for express apps.
app.use("/users", userRouter);
// Call app.use, passing in the function bodyParser.urlEncoded, which
// takes a single object as an argument, with the key extended
// and value false. This allows express to parse body data from an
// HTML form.
app.set("view engine", "pug");
// Call app.use, passing in the function bodyParser.json() as the argument.
app.get("/", (req, res) => res.sendStatus(200));
// Require './routes/user', destructuring the named export userRouter
// from inside of it.
const init = async () => {
await connect();
app.listen(port, () => console.log(`Express is listening on port ${port}`));
};
// Call app.use, which takes two arguments: "/users", and userRouter.
// This sets up a "sub-router" for our express application, which nests everything
// inside of the /users section of our app.
// Set the view engine of express to pug.
// Define a root route "/" that sends a status of 200 back to the user.
// Define an async function "init", which calls:
// - the connect function (use await)
// - (optionally) drops the database whenever the app is started,
// using mongoose.connection.dropDatabase() (use await for this)
// - app.listen, passing in the port and a callback function which logs
// the port our express app is listening on
// Call the init function.
init();
// Require mongoose and set it to the variable mongoose.
// Define userSchema, which is the value of calling mongoose.Schema,
// passing in an object where:
// - id is a Number
// - name is a String
// - description is a String
// - created_at is an object with type Date and default Date.now
// - updated_at is an object with type Date and default Date.now
// Define the variable User, which is the response of calling
// mongoose.model with two arguments: the string "User" and userSchema.
// Next, we'll define some helper functions used to assist lookups
// in our Mongo collection.
// These functions will all build off of the User model, with the
// end-goal of having each function be "chainable" via promises.
// Note that any **query** in mongoose does _not_ return a promise:
// for these, we'll have to chain .exec() on the end of it to
// explicitly return a promise.
//
// e.g. Todo.find().exec() <- exec() chained on the end
// getUsers is a function that calls User.find(). Chain .exec() on the end of this
// function.
// getUser is a function with an argument id, that returns the result of calling
// the User.findOne, passing in an object with a key and value of id. Chain
// .exec() on the end of this function.
// createUser is a function with an argument body, that returns the result of
// creating a new instance of the User class, passing in the body argument.
// Chain .save() to the end of this new User call.
// updateUser is a function that takes two arguments, id and body.
// It returns the function User.findOneAndUpdate, passing three arguments:
// - an object with key and value id
// - body
// - an _options_ object with new set to true. This indicates that
// mongoose should return the _new_ version of this updated object
// Chain .exec() to the end of this function
// deleteUser is a function that takes an argument id, and calls User.deleteOne,
// passing an object with key and value id.
// Finally, export each of our helper functions from this file:
// - getUsers
// - getUser
// - createUser
// - updateUser
// - deleteUser
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
id: Number,
name: String,
description: String,
created_at: { type: Date, default: Date.now() },
updated_at: { type: Date, default: Date.now() }
});
const User = mongoose.model("User", userSchema);
const getUsers = () => User.find().exec();
const getUser = id => User.findOne({ id }).exec();
const createUser = body => new User(body).save();
const updateUser = (id, body) =>
User.findOneAndUpdate({ id }, body, { new: true }).exec();
const deleteUser = id => User.deleteOne({ id });
module.exports = {
getUsers,
getUser,
createUser,
updateUser,
deleteUser
};
......@@ -17,50 +17,29 @@
// and redirects to /users/:id of the new user
// To start, let's import a couple things.
// First, we need to import express - specifically, the "Router" function
// from inside of request. Either require express as a variable, and then
// set the variable Router to express.Router, or just destructure Router
// out of the express require call.
// Next, define userRouter, which is the response of calling the Router
// function.
// Next, import the following named functions from the user file in the
// models directory:
// - getUsers
// - getUser
// - createUser
// Now we can define our first route. Call userRouter.get, passing in the
// path "/", and defining an **async** callback function.
// This function should set the variable users to the value of getUsers
// (using await to wait for the async method getUsers to finish),
// and then should render the template "users/index", passing in a data
// object where users is set to the key users.
// Our next route is another get request, this time to "/new".
// It should render the template "users/new".
// Our next route is a get request at "/:id", with another async callback
// function.
// This function sets id to the value of params.id inside of our request.
// It also defines the variable user, which is the value of calling getUser
// with id (make sure to use await). Render the template "users/show", passing
// in a data object with a key and value of user.
// Our next route is a post to the root route, "/". The callback function
// (async) function sets body from of request.body. It then calls createUser,
// passing the body variable into the function (use await). Set this variable
// to user. Once the user has been created, we should redirect to the user
// route, using res.redirect. Pass in the url /users/:id, where id is the
// new user id.
// Finally, set module.exports to an object, passing in userRouter
// (so userRouter is a _named_ export of this file).
// Make sure that you also look at the files inside the views folder,
// which have some Pug functionality for you to implement so you can actually
// view your users in-browser.
const { Router } = require("express");
const userRouter = Router();
const { getUsers, getUser, createUser } = require("../models/user");
userRouter.get("/", async (req, res) => {
const users = await getUsers();
res.render("users/index", { users });
});
userRouter.get("/new", (req, res) => {
res.render("users/new");
});
userRouter.get("/:id", async (req, res) => {
const id = req.params.id;
const user = await getUser(id);
res.render("users/show", { user });
});
userRouter.post("/", async (req, res) => {
const body = req.body;
const user = await createUser(body);
res.redirect(`/users/${user.id}`);
});
module.exports = { userRouter };
//- For each user in the users array in data,
//- render an h1 tag that has a value of user.name
for user in users
h1 #{user.name}
//- Define a link tag with an ahref of /users/new, and the text
//- "Create a new user"
a(href="/users/new") Create a new user
//- Define a form tag with the following attributes
//- - action is "/users"
//- - method is "POST"
form(action="/users" method="POST")
div
label(for="id") ID
input(type="text" name="id")
//- Inside of the form, add four divs.
div
label(for="name") Name
input(type="text" name="name")
//- The first div has a label with an attribute "for" set to "id",
//- and text "ID".
//- It also has an input with type="text" and name="id"
div
label(for="description") Description
input(type="text" name="description")
//- The second div has a label with an attribute "for" set to "name",
//- and text "name".
//- It also has an input with type="text" and name="name"
//- The third div has a label with an attribute "for" set to
//- "description", and text "description".
//- It also has an input with type="text" and name="description"
//- The fourth div has a button with type="submit", and the text "Create user"
div
button(type="submit") Create user
//- Define an h1 with the text #{user.name}
//- Define an h2 with the text "Created #{user.created_at}"
h1 #{user.name}
h2 Created #{user.created_at}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment