MongoDB Working with APIs and Practical Examples

Video Tutorial


After Going through the basic setup on MongoDB and how it actually works, it is time to move on making a bit more advanced apps on MongoDB and we are going to reimplement the Pokemons-api that we have covered HERE moving on from static arrays into storing and retrieving the data from a real database which is, in this case, is going to be MongoDB, we are going to cover the get add and delete operations.

Integrating MongoDB

Now on the Pokemon-API, we have stored the Pokemon’s name and ability on a static array on the server which means whenever the server is restarted the array is going to be reverted to default which is not recommended at all but still does the job perfectly, so we need to move on storing and fetching the data from a MongoDB Database and using Mongoose to connect to it since we are using Node.js for our Server, first we implement the Get all Pokemon List

The Default data is stored on a static array

let pokemons = [
    { name: "Bulbasaur", ability: "Overgrow" },
    { name: "Charmander", ability: "Blaze" },
    { name: "Blastoise", ability: "Torrent" },
    { name: "Metapod", ability: "Shed Skin" },
    { name: "Paras", ability: "Effect Spore" }

So first we need to create a schema and compile it into a model in order to be able to interact with the database

//Create the  Schema 
let PokemonSchema = new Schema({
    name: {
        type: String,
        required: true,
    ability: {
        type: String,
        required: true
//And Compile it into a Model 
let Pokemon = mongoose.model("Pokemon", PokemonSchema);

Since we have the model now we can fetch the data from the database in order to send it back to the client who made the request.

And Unlike SQL Databases MongoDB Requires you to have the Schema (Model) of the data you want either to fetch or save to the database, so the model needs to be presented whenever you need to interact with the it

Let’s try to find and Send the All Pokemon List

//Find All Pokemons
Pokemon.find({}, (err, pokes) => {
    if (err) res.status(501).send("Error Message!");
    res.json({ status: 'Success', message: "Pokemons Fetched Successfully!", pokemons: pokes });
//We use the Find Method Under Our Model

As you can see we use the find method and passing in the Object we want to find in this case since we need to get all of the Pokemon so we use an empty Object to tell it to grab us everything on this Collection (Table)

Adding, Updating and Deleting from Database

After we have seen the basic operation of find or searching the database for all of the available Pokemon now we need to be able either to update add or delete a specific record, this get even simple when using a module like mongoose since it makes all the needed operations very straightforward

For Adding New Pokemon when we submit the /addPokemon Route we edit the Post method of the Route

//We create an Instance of a Pokemon using the Specified Name and Ability 
let poke = new Pokemon({ name: req.body.pokeName, ability: req.body.pokeAbility });
//Now we save the Instance to the Database using the Save Method and Send a Response to the USER, newPoke) => {
        status: "Success",
        message: "Pokemon Added Successfully!",
        reload: true

You can Now use Postman to submit a request and analyze the response while adding is very simple also updating and deleting more simple, for updating an already exists data on the database

//We use the FindByIdAndUpdate Method for updating a record using it's ID 
Pokemon.findByIdAndUpdate(PokemonID, {name: "NewName"}, (err, newPoke) => {
   console.log("Pokemon has Been Updated ", newPoke);

Mongoose gives you a very easy to use API methods that can do the Basic Operations that you may need to use, the same thing for deleting a record

//We use the FindByIdAndRemove method to search for a specif record using it's ID
Pokemon.findByIdAndRemove(pokemonID, (err) => {
   if(err) console.log("Error cannot Delete!");
   else console.log("Pokemon Removed Successfully!");

And here we are, either you want to add, update or delete a record (Pokemon) from the Database that is going to be very easy for you.

Since we haven’t Implemented the Update and Delete Operations on our API so we can use from the Client Side you can take that as an Excercise and Make it by your own just tiny challenge for you to achieve.

No Comments Yet