How to add data on MongoDB using Node-Express API


In this tutorial we are going to do two important things

  • Create an API which is capable of perform CURD operation on MongoDB server
  • User the API to perform CURD in a web app

Making of the API

MongoDB is NoSQL database which is capable of running on the cloud and local alike.

  • How to create an API using Express in Nodejs

    API is an essential part of modern apps and web applications, it allow users to perform CURD operations using one single web interface. An identical API uses JSON structure to store and retrieve data. It is suitable for mobile app or another web app.

    One of the advantage of API is that it can be utilized by multiple applications. It also mean that the CURD operation need not be write again again and again in each applications.

    Not sure where to start learning ?, check out these Node tutorials

    API

    Let’s create a simple API using

    • Express
    • Joi
    • Nodejs

    Express

    Express help us create and manage web app pages or routes, it is the simplest way to create a web app in Nodejs. Many other NodeJS frameworks are build up on Express as the root.

    JOI

    JOI is a NPM package which help us create a schema for our API and validate.

    The source code

    const Joi = require("joi");
    const express = require("express");
    const app = express();

    app.use(express.json());
    const courses = [
    { id: 1, name: "course 1" },
    { id: 2, name: "course 2" },
    { id: 3, name: "course 3" },
    ];
    app.get("/", (req, res) => {
     res.send("Hello world");
    });

    app.get("/api/courses", (req, res) => {
     res.send(courses);
    });

    app.post("/api/courses", (req, res) => {
     const schema = {
       name: Joi.string().min(3).required(),
    };

     const result = Joi.validate(req.body, schema);
     if (result.error) {
       res.status(404).send(result.error.details[0].message);
       return;
    }
     const course = {
       id: courses.length + 1,
       name: req.body.name,
    };

     courses.push(course);
     res.send(course);
    });

    app.delete("/api/courses/:id", (req, res) => {
       const course = courses.find((c) => c.id === parseInt(req.params.id));
       if (!course)
           return res.status(404).send("The course not found");
           
     
       const index= courses.indexOf(course)
       courses.splice(index,1)    
       res.send(course)
    });

    function validateCourse(course) {
     const schema = {
       name: Joi.string().min(3).required(),
    };

     return Joi.validate(course, schema);
    }
    app.get("/api/courses/:id", (req, res) => {
     const course = courses.find((c) => c.id === parseInt(req.params.id));
     if (!course) res.status(404).send("The course not found");
     res.send(course);
    });

    const port = process.env.PORT || 3000;
    app.listen(port, () => {
     console.log(`listen on the port ${port}`);
    });

    The app has 5 APIs to perform CURD operations, as you noticed that all API routes are organized in the /api/ route which is a common standard. A secure API also uses a security key to access the data.

    The API add,remove,delete,update courses. For update the data I used PUT method which is actually update all the data. .An alternative to this is a PATHCH which update one only one

    The Slice method is used to remove data from the collection, Push is used to add a new data and find will fetch data from the JSON collection.

    How to run and Test API

    As you may noticed that this app don’t have UI for operations. API usually lack , because they are meant for developers and not to all users, so UI is less important. In order to test the API you should have Postman Like application, where you can test POST,GET,PUT APIs. Postman can be used for free, all you need to register and download the desk app for your plat form.

    In the New / Next to Launch Pad you can create, test new request and in the Body – > raw you can use JSON data.

$(function () {
// code block here
}

HTML Web app

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

Using the API – GET and POST request

The GET request is used to get a list of data, says product list,users list, customer list etc and the POST send data to the server. By default API call will make GET request

POST API Call using jQuery and AJAX


With JQuery ( light weight, super Java Script library) we can handle events, dynamically add content to html blocks.

Let’s learn how to make a POST API request in HTML/web app using jQuery and AJAX? POST request used to send data to the server.

jQuery

jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.

$(function () {
// code block here
}

HTML

In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.

  <script src="/jquery.js"></script>  -- local version of jQuery library
  <script src="/public/script.js"></script>  -- our script

How to make POST API request

In this example we are about to add data into the server using API POST method.

The GET request is used to get a list of data, says product list,users list, customer list etc and the POST send data to the server. By default API call will make GET request

In the script file you can add following code to access the API, in our example it is a list of users

 $("#submit-btn").on("click", function () {
    var inputUname = $("#input-uname");
    var inputEmail = $("#input-email");
    var inputPass = $("#input-passwd");
  
    $.ajax({
      url: "/api/user",
      method: "POST",
      contentType: "application/json",
      data: JSON.stringify({
        uname: inputUname.val().trim(),
        email: inputEmail.val().trim(),
        pass: inputPass.val().trim(),
      }),
      success: (response) => {
        alert("New user created");
        inputUname.val("");
        inputEmail.val("");
        inputPass.val("");
        $("#btn-get").click();
      },
      error: (err) => {
        alert("Please fill the boxes");
      },
    });
  });

the AJAX call is made inside the document ready function, which will execute only after the complete web page is loaded. The ajax call has following properties

  • url – the API itself
  • contentType – type of the content , it can be json structured in many cases.
  • method – POST/GET
  • data – a JSON data to the server
  • Success – function that will execute after the call made successfully
  • error : – can be arrow function for handling errors

The success function return a response , in which our retiring data is packed. In this example the new user object.

Some jQuery post will help you to extend the functionality of your app.

SnackBar without using scaffold or state key in Flutter


SnackBar is used to show some quick information to the user in Android app. Flutter allows you to use SnackBar with scaffold or ScaffoldState key / Global key.

The Get Framework, dependency management tool, allows you to use SnackBar and without using scaffold. Get has its own dependency /state management system so we need not feel the pain.

So how how do we use it , add the dependency first at yaml file

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  get:

import

import 'package:get/get.dart';

import the package and go on with Snackbar

Get.snackbar(title', 'message');

You can use SnackBar options in case miss something. Forget the Scaffold for a while. Get is lightweight ,secure and fast.

You may also interested in these Get tutorials

Update StatelessWidget UI dynamically using Get in Flutter


As we know StatefullWidget can update UI using setState ( ) method. When we made changes in the variable binded to a UI , changes can be made possible with SetState. How about StatelessWidget ?

Usually StatelessWidget redraw UI by the parent widget. Suppose you had a Cart page in which add new products to the shopping cart, which is a StatelessWidget. Need to update the count of items and bind to the UI, so it can dynamically update.

The Get Framework, Sate management tool, here to help and manage state of widget for you. Get has its own dependency /state management system so we need not feel the pain. Continue reading Update StatelessWidget UI dynamically using Get in Flutter

Use ‘Get’ navigation manager to switch route /page in Flutter


Heard about Get , a light weight Flutter framework for developing apps with a smart Navigation manager. So what’s make Get Special, Is Flutter has Navigator to do what you want to do ? Yeh. But Get is smart and fast and it is one of the top package on pub.dev

How to use Get

Go to pubspec.yaml file add it as dependecies and also add an import statement to the top of your .dart file.

</p>
dependencies:
  flutter:
    sdk: flutter
  get:

<p>
</p>
import 'package:get/get.dart';
<p>

Get can be used to move to another widget page/route or simply calling Get.to . A prerequisite for this is a small change in main, replace the MeterialApp constructor with GetMaterialApp

</p>
void main() async {
   runApp(new GetMaterialApp(
    home: new MyApp(),
  ));
}
<p>

Suppose I have widget screens like ProductPage, I want to replace conventional flutter way of calling the push with Get.

Navigator.push(context,
     new MaterialPageRoute(builder: (context) => (Product())));

can replace with

</p>
Get.to(Product());
<p>

Get can be useful on various occasions, I save it for another post.