Now in the last lesson we solved some of our problems namely how do we get some default items into our
ToDo list to start off without having to use arrays and instead getting this from MongoDB database.
There's just one problem.
If I tried to add a new item right now then my app will crash because again it's telling me there's an
array called items that we used to use down here no longer exists and I can't really push something onto something
that doesn't exist anymore right?
This happens in our post route and that is when we decide to add a new item and we trigger the form
to post to our root route which gets caught in here and we try to grab the item that the user tried
to post and then we try to push it into our items array.
How can we do this using MongoDB instead?
Well for now I'm going to completely ignore the fact that we had a work route and a normal route.
I'm going to simply delete all of this.
We know that when this post route is triggered we can tap into something called req.body.
newItem and that will refer to the text that the user entered into the input when they clicked on the
plus button to add that newItem. That text
I'm going to save into a constant called itemName. And then I need to create a new item document based
off my model in MongoDB. As a challenge
I want you to pause the video and create this newItem document using this itemName that got passed
over.
Okay. So this is exactly the same as what we did up here when we created new documents.
We're going to write const item = new Item so create it from the item model with Mongoose and then
that item only has a single field which is called name and the value we're going to give it is going
to be the item name that we got passed over from our list.
ejs.
Now that we've created our new document, then instead of insertMany or using some of the other insert methods,
we could actually just use the Mongoose shortcut by saying item.save and that will save this item
into our collection of items.
So now if we hit save and we go back to our localhost: 3000 and we go ahead and hit enter to refresh
our web page, then
now if I added a new item here and I hit +, then I head over to my Mongo shell and I say "show dbs"
"use todolist
DB". "db.dot items.find" and you can see I now have 4 items.
So it was successfully saved into my items collection.
In order to get it to show up here all we need to do is just to redirect-- res.redirect back over
to the home route.
So now after we save our item then we re-enter over here and we find all the items inside our items
collection and render it on the screen.
Let's again test our app localhost:3000
let's add a new item
hit +, redirects to the home route and we see it update immediately.