Step 6

Let's register a user!

Update route handler for POST /register in index.js:

app.post("/register", async (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  console.log(colors.cyan("Register:", { username, password }));
  try {
    // TODO register the user!
    const user = await users.create({username, password});
    console.log(user);
    // redirect to the login page
    res.redirect("/");
  } catch (err) {
    console.log(err);
    res.json(err);
  }
});

Notice we simply print the error to console and return it to the client. This is not a good strategy to deal with errors! We will leave it for now however to focus on the registration process and good practices.

Also notice, the handler function is decorated with async keyword

app.post("/register", async (req, res) => {
  // notice the async keyword!
});

Finally, note you must include the following import statement in index.js

const users = require("./model/User.js");

Save index.js and go to http://localhost:5001/register to register a user:

You must the user object printed to the terminal (once it is created)

{
  _id: '5faab2d28853463591a63b4c',
  username: 'madooei',
  password: '1234',
  __v: 0
}

And check your MongoDB database to ensure the data is saved there