In part 1 of building our todo app we set up our Mongo database, express, ejs, and our body parser. It is ready and listening.
Adding Seed Data
Now it’s time to add seed data. Seed data is initial data when you first create the database it’s empty and you seed it with its initial data. Usually it’s for your application but sometimes for sample user data. Now to do this I created a controllers folder. Inside the folder I created a file called setupController.
In setupController I require a land export the todo module we created in part 1. Then I created some fake data with JSON generator to test large data. We are just creating JSON objects that work throughout the MEAN stack.
With our new dummy data we use the .create method to create these objects and run it.
From there I just ran nodemon in the command terminal and checked to see if the data ran in the local server in the browser.
Creating Our API
With the seed data initialized it is time to build our API. The API I created is for multiple integrations so that it can be used for different devices etc. So, the first step in these is to create another file in the controllers folder named apiController. First two lines of code inside of this file will be to require todoModel module and body parser.
After writing the code to use body parser for JSON and url encoding, we’ll have to get all the to do’s for a particular person. Another method that can be used with app is .get. The colon username means, that that can be a parameter that can change url and I can get what that value is with request.param, so I’ll just call it req, request response.
Next we’ll build another API for individual todos. In this case we’ll get particular to dos by ID. Mongo assigns an ID to anything that’s put inside of it and mongoose provides a findById method.
After this we will now add a to do, so I’m gonna post some data that’ll be a http post. This request will be a post as its a method and if I post /api/todo, it’ll be JSON.
Last thing will be to allow a delete and this will be an http request whose method is delete.
That’s it I can get all of the to dos for a person, get a particular individual to do, a new to do, and I can delete a to do. The final thing to do is to require our apiController in the app.js.