Skip to main content

How to Save Form Data in Mongodb Database using Node.js

  In this tutorial we will learn how to save data from the Form in Mongodb database using a Node.js app. We will create a simple form in html in front end and use node.js as backend server to post or save the data into mangoose database. In the previous blog post, we just learned how to submit the form data using javascript, but in this blog we will learn a little advanced concept of saving the form data into a database. To learn about how to save data from a form in Mongodb database using node.js, you need to have some basic understanding of node.js, mongoose, and html. 1. Creating a Node.js app Open the command terminal on your computer and type below commands in it. mkdir sample-app cd sample-app npm init -y   2. Install Dependencies In order to successfully run our application, we need to install some dependencies as mentioned below: Mongoose: Mongoose is a Object Data Modelling library for node.js. It helps in object mapping, creating collections, saving and retrievi

API Documentation Overview

 In this blog, we will explore an example of API documentation for one example function findNeedles().

findNeedles()

Overview

The purpose of the findNeedles() API takes two string parameters i.e. needles array and haystack and finds the total number of occurrences of each element in the needles array that are present in the haystack string.

This function searches for only five words or less from the needles array and logs an error if more words are available in the needles array.

The comparison is done by first splitting the haystack string using literals like backspace, tab space, single quote, and double quote etc into single elements and then looping over the needles array to find occurrences of these elements.

Parameters

This function takes following parameters:

Name

Type

Description

haystack

String

A string of any length

needles

String Array

An array of words  

 

Sample Code

	

public static void findNeedles(String haystack, String[] needles)

 {

      if (needles.length > 5)

     {

System.err.println("Too many words!");

      } else

     {

int[] countArray = new int[needles.length];

for (int i = 0; i < needles.length; i++)

          {

String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);

              for (int j = 0; j < words.length; j++)

          {

if (words[j].compareTo (needles[i]) == 0)

{

countArray[i]++;

}

           }

        }

     for (int j = 0; j < needles.length; j++)

         {

System.out.println (needles[j] + ": " + countArray[j]);

         }

   }

}

Output

If the length of the needles array is less than or equal to five, then this function displays each word in needles array along with the total occurrences of it in haystack as shown below:

[needle_1]: number of occurrences

[needle_2]: number of occurrences

[needle_3]: number of occurrences

[needle_4]: number of occurrences

[needle_5]: number of occurrences

 

Error Message

If the needles array contains more than five words, the following error displays:

“Too many words!”

Calling the Function

This function takes in two parameters, a ‘haystack’ input string and a string array ‘needles’ containing words for which occurrences need to be found.

String haystack = “Quick Brown Fox Jumps Over The Wall”;

String[] needles = {“Quick”,“Jumps”,”Wall”,”Fox”, “Brown”}

findNeedles(haystack, needles);

Example Test Cases

Case 1:

String haystack = "Apple Orange Fruit";

String[] needles = {"Apple","Orange","Fruit"};

Result:

Apple: 1

Orange: 1

Fruit: 1

 

Case 2:

String haystack = "Apple Orange Fruit";

String[] needles = {"Apple","Orange","Fruit","Banana","Table","Mango"};

Result:

Too many words!

 

Case 3:

String[] needles = {};

String haystack =  ”Apple Orange Fruit”;

Result:


Case 4:

String haystack = "";

String[] needles = {};

Result:

 

Case 5:

String haystack = "A p p l e Orange Fruit";

String[] needles = {"A p p l e","Orange","Fruit"};

Result:

A p p l e: 0

Orange: 1

Fruit: 1

 

Limitations

·         The needles argument can accept only 5 search words. If this number exceeds, it shows an error.

·         This function can only search for single words in haystack string and cannot recognize words if space is there between letters. It also cannot recognize if phrases are provided.

·         The search words are case sensitive. “Apple” and “apple” are considered different.

 

Commented Code

class Main {

  public static void main(String[] args) {

    String haystack = "Apple Orange Fruit"// declaration of string haystack with some string value.

    String[] needles = {"apple","Orange","Fruit"}; // declaration of string array containing words to search in haystack.

    findNeedles(haystack, needles); // calling the findNeedles function with arguments haystack and needles. 

  }

  public static void findNeedles(String haystack, String[] needles) //this function searches for how many times each element in the needles array occurs in the haystack string.    

 {

    if (needles.length > 5

    {

        System.err.println("Too many words!"); //display an error if needles array contains more than 5 elements.

    } else //else case starts

    {

      int[] countArray = new int[needles.length];//creates a countArray of type integer with size equal to length of needles array.

      for (int i = 0; i < needles.length; i++) //initiates a loop to iterate over each element of needles array.   

          {

            String[] words = haystack.split("[ \"\'\t\n\b\f\r]"0);//create a new string array words that contains the result

                                                                    // after splitting the haystack by delimiters like tab, new line etc.

              for (int j = 0; j < words.length; j++)// initiate a loop to iterate over each element of words array

           {

                if (words[j].compareTo (needles[i]) == 0//compare each string in words array with each string in needles array 

                {

                    countArray[i]++; //if a particular string in words and needles matches, increment the countArray array by 1. 

                }

            }

        }

     for (int j = 0; j < needles.length; j++) //initiates a loop to iterate over each element in the needles array

         {

            System.out.println (needles[j] + ": " + countArray[j]); // display each element in needle array with its corresponding value in the countArray indicating total number

 of occurrences.

         }

   }

 }

}

 

Suggestions for Improvement of Code

·         Call the split function before the For Loop to improve performance and to reduce CPU and memory usage as split function will get called only once.

 

else {

          int[] countArray = new int[needles.length];

          String[] words = haystack.split("[ \"\'\t\n\b\f\r]", 0);

          for (int i = 0; i < needles.length; i++) {

              for (int j = 0; j < words.length; j++) {

                  if (words[j].compareTo(needles[i]) == 0) {

                      countArray[i]++;

                  }

              }

          }

 

·         Regex search can be utilized to compare words in ‘needles’ array with haystack string. This ensures reduction in memory usage. Moreover, using regex for search helps to overcome existing shortcomings like non-support of phrases, punctuation, case-sensitive text etc.

·         New enhancements can be brought in where user can be asked to search for desired word from the needle array.

 

 

Comments

  1. How to Play Baccarat - FEBCASINO
    Learn how to play baccarat 인카지노 using the online poker site. the tables are very deccasino high 바카라 사이트 so players will enjoy the game.

    ReplyDelete
  2. The Most Successful Sites for Crypto, Casino & Poker - Goyang
    Goyang Casino & poormansguidetocasinogambling Poker is one www.jtmhub.com of the most famous and well known crypto gambling sites, founded 바카라 in goyangfc.com 2012. nba매니아 They are popular because of their great

    ReplyDelete

Post a Comment

Popular posts from this blog

Understanding Intents in Dialogflow

Dialogflow is a highly robust and dynamic natural language understanding platform that allows you to quickly build highly scalable conversational chatbots by leveraging the power of Artificial Intelligence (AI). You can easily create highly customizable chatbots for variety of channels like web applications, mobile applications, Facebook page, social media apps and much more. It provides seamless integration with variety of channels like Facebook, Viber, Telegram, Slack and much more. But in order to start working on building a chatbot yourself, lets connect the dots to get a clear picture of entire chatbot development process in Dialogflow. To create a chatbot, let us understand some of the nuances of the Dialogflow. What are Intents? Intents help Dialogflow ascertain the real intent or motive of the user messages. You can provide a set of certain training phrases that can help Dialogflow get trained to recognize similar such phrases and trigger a specific intent whenever such

Using Entities in Dialogflow to Extract Vital Information

Having learned about Intents in our previous blog , in this blog we will shed light on another interesting topic of Entities in Dialogflow . Entities provide an efficient way to capture and extract crucial information like name, country, location and any custom information from user inputs. Entities can be mainly categorized into three types: 1.  System Entities : These are build-in entities provided by Dialogflow through which you can identify and extract most common type of data like name, country, date, email address etc. 2. Custom Entities : These are user-defined entities that are useful to extract custom data from the user inputs. For example, you can define a Fruit entity type that can identify and map different fruit types like Mango, Apple etc.        3.  Session Entities : As the name suggests, these entities remain active only for the session for which they have been created. They provide additional capability through which we can update custom entity types with new