Fix MongoError on first connect

The default MongoDb port is 27017. An error occurs sometimes while I am running my Node & ExpressJS application, with the message:

message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]' }

Several solutions are provided on the internet to fix this. But a lot of them did not work for me. The simplest method I find to fix this on MS Windows is:

1. Open your Command Prompt as administrator.
2. Type > net start mongodb

The mongodb service starts successfully.

Template literals

I have to print a message with values of, say, two variables interpolated or inserted in it. I am talking about JavaScript here. What I do is start single or double quotes, write some part of my message string, close the quotes, insert the variable, start quotes for remaining part of the message and keep going. If the number of variables is more, it’s a pain in the ass. Sometimes one tends up forgetting closing quotes somewhere and then check out the point of error. This can be illustrated as:

var person = {name: "Kamalpreet", age: "24"};
console.log("My name is " + person.name + " and I am " + person.age + " years old.");

This has been simplified by EcmaScript6 (ES6). The third type of quotes, the back-tick ones are used to escape all this fuss. The back-tick quote is used along with $() to contain the variable syntax. An illustration for the same example above is shown below:

console.log(`My name is $(person.name) and I am $(person.age) years old`);

Same output is shown by using both the methods. Latter one is simple and a part of ES6. This is called template literals or template strings. Another point that differentiates template literals is the definition of the string can be spanned across multiple lines without use of linefeed character. For an instance,

console.log(`Hello, my name is 
${person.name} and I am ${person.age}
years old`);

Prior to the introduction of template strings, this would have been done as:

console.log("Hello, my name is " + \
person.name + " and I am " + person.age + \
" years old");

These were few simplifications towards cleaner code introduced in ES6. There are few more which I will write about as I learn.

Some methods of arrays

Iteration of arrays can be done via use of a map function instead of using for loops. Given an array, each element of the array is operated upon. Function creates a new array instead of updating the existing one.

// Multiply each element of oldArray with 3 to create a newArray
var newArray = oldArray.map(function(val) {
    return val * 3;
});

I have to add all numbers in an array. What I have learned since beginning is use a for loop to iterate over the length of an array while adding them to an accumulator variable. Similar operation can be performed using the reduce function. currentElement as the name denotes is the item of the array currently iterated.

// Sum using reduce function with default value of 'sum' is set to '0'
var sum = array.reduce(function(sum, currentElement) {
    return sum + currentElement;
}, 0);

The filter method is used to query arrays and filter out elements depending on the condition specified. This is equivalent to iterating through all elements using for and then using a conditional statement, depending on the results of which the elements are stored in a vector or array or some other data structure. A new array is created when this is used.

// I need only elements that are less than 5 i given array.
var oldArray = [1,2,3,4,5,6,7,8];
var newArray = oldArray.filter(function(val){
    return val < 5;
});
// newArray = [1,2,3,4]

The sort method sorts the elements of the array and the array being operated upon is altered. No copy of the existing array is made. Arrays of strings can also be sorted.

// Sort elements of array in ascending order, 'a' and 'b' are elements being compared at a time
array.sort(function(a, b){
    return a-b;
    // If sorting in descending order, return b-a
});

It is to be noted that a negative value returned implies element ‘a’ is smaller than ‘b’ and hence should be assigned a smaller index. A value greater than 0 implies the larger index value should be assigned to ‘a’ and when equal to 0, means both ‘a’ and ‘b’ are equal.

reverse reverses the elements of the array.

var array = [1,2,3];
var reverseArray = array.reverse()

concat is used to merge the contents of two arrays into one. It takes an array as an argument and returns a new array with the elements of this array concatenated onto the end of the array on which this operation is applied.

var array = [1,2,3];
var concatArray = [4,5,6];
var newArray = array.concat(concatArray);
// newArray = [1,2,3,4,5,6];

I have a string and I want to tokenize it into different elements and save that in an array. split does this depending on the delimiter passed in as argument to this function.

var stringToSplit = "I am learning how to split";
var array = stringToSplit.split(' '); // space is used as delimiter here.

On splitting, array has 6 elements for each word in the string.

Next function is join which joins the elements of the array to form a string.

var hobbies = ["reading", "writing", "drawing"];
var hobbiesStr = hobbies.join(" and ");
console.log(hobbiesStr); // reading and writing and drawing

These are few of the methods available for arrays which ease up performing the corresponding functions without having to iterate and compare or append manually. So JS makes these things easier with the pre-defined functions.

Objects in JS

Objects in JS can be created by:

  1. Use of variables
  2. Use of functions
// table variable                      |              // use of function
var table = {                          |              var table = function() {
    "legs":4,                          |                  this.legs = 4;
    "color":"brown",                   |                  this.color = "brown";
    "material":"wood"                  |                  this.material = "wood";
};                                     |              };

An instance of these objects can be created as:

var myTable = new table();

Arguments can be passed as needed in the constructor with corresponding changes in definition of the constructor. All the variables defined as property of this are public. In order to make a variable private, var keyword is used. Private variables are created to control changes that happen to their values from outside. Functions to modify these values are then defined within the constructor. This is illustrated in Bike object below.

var car = function() {
    var speed = 20;            // private variable

    // public methods below
    this.accelerate = function(paceup) {
        speed += change;
    };

    this.decelerate = function() {
        speed -= 5;
    };

    this.getSpeed = function() {
        return speed;
    };
};