Skyrockit Build Create Functionality
Learning objective: By the end of this lesson, students will be able to implement and understand the ‘Create’ operation in a CRUD application by setting up a RESTful POST route in an Express application.
With our form in place for adding new job applications, the next critical step is to establish the route that will handle the form data and create a new entry in our database. This is where the ‘Create’ operation in our CRUD functionality comes into play.
Conceptualizing the route
According to our RESTful routing chart, the route responsible for creating a new job application is a POST request. This type of request is used for sending data to the server to create a new resource. In our case, the route will look like this:
POST /users/:userId/applications
This route signifies that we are posting new job application data associated with a specific user (identified by :userId).
Update the form action in new.ejs
Now, let’s update the <form> in our new.ejs file to ensure it sends data to the correct route. Modify the form’s action attribute to match our future POST route. The method attribute should be set to POST as well, indicating the type of request we’re making:
<!-- views/applications/new.ejs -->
<form action="/users/<%= user._id %>/applications" method="POST">
<!-- Form inputs here -->
</form>
By setting the form’s action attribute to our POST route, we direct the form data to the appropriate server endpoint when the form is submitted. The user._id in the action URL dynamically inserts the current user’s ID, ensuring the new job application is associated with the right user.
Defining the route and coding the controller
Next, we need to build the route we listed in our form action. In our applications controller, let’s create the following:
// controllers/applications.js`
router.post('/', async (req, res) => {
try {
// Look up the user from req.session
const currentUser = await User.findById(req.session.user._id);
// Push req.body (the new form data object) to the
// applications array of the current user
currentUser.applications.push(req.body);
// Save changes to the user
await currentUser.save();
// Redirect back to the applications index view
res.redirect(`/users/${currentUser._id}/applications`);
} catch (error) {
// If any errors, log them and redirect back home
console.log(error);
res.redirect('/');
}
});
🧠 Note: We’re directly pushing the
req.bodyobject to the current user’sapplications, which is why it was so important that the key:value pairs generated by the form match perfectly with our schema. Any mistakes in matching will result in lost data, as Mongoose will reject anything that is not defined inside of the schema.
With that, our two-step new and create functionality is complete. While the entire create process is invisible to the user, it’s still a necessary step in completing the first user story. Without a POST route, and a controller to manage the incoming form data, the user would be submitting data to nowhere rather than saving it to a database.
Testing your route
Sign in and test your new form. If the data was successfully saved you should be redirected to the applications page. You can also check your database in the MongoDB Atlas dashboard.