Node.js REST, Mongo tips

  • In express library functions: post(), get() will stop the execution of code if you write return. It’s like in any other function in programming. keyword return will always stop the function execution.
  • When you write (res is the response callback function) res.end(), res.json(), res.send(), in other words when you end the response you cannot utilize res callback again it becomes irrelevant since you completed your restful service with a response. If you have any code after res.something() it will execute till you specify a return but res will not be available anymore. If you use it however, it will throw an error.
    Refer: Execute code after res.end() (StackOverflow)
  • You don’t need to return res.end(), json(), send() if you don’t have code which needs to execute after it.
  • If you don’t have anything to send to the Frontend side then use res.end() to complete the service action.
  • Use next function, specified at the end of restful service callback function:
    .get((req, res, next) => {action}

    to catch errors and forward them to the middleware:

    if (err) {
        return next(err);

    the return next() will go to the already built in error handler and will result with a 500 XHR failed request on the Frontend. Also applies for catch() blocks, having next(err) will also result with Node.js built in error handler execution giving 500.

  • A Node.js mongoose query is not a JS Promise. They just represent a async operation which returns a then so that you can apply: query().then(res=>console.log(res));
    Refer: Mongoose async queries (StackOverflow)
    If you want a real instance of JavaScript Promise then put an exec() after your “fake” Mongoose query promise: query().exec().then(res=>console.log(res));
  • The default status for res.send(), res.json() is 200 thereby no need for res.status(200).send() or res.status(200).json();
  • In Mongoose findOneAndUpdate query
    User.findOneAndUpdate(findQuery, updateData, {
    upsert:true represents that if the record doesn’t exist a new one will be created/inserted
    useFindAndModify:false removes deprecation warning
    new:true gives the response of updated data, otherwise you get the data of the current findQuery record.
    I like to specify those parameters for each query so that I know what to expect from it.
  • ObjectId(userId) vs
    new ObjectId(userId) are the same, use whichever one you like but be consistent once you pick one.
  • Do not close your mongo database connection after terminating your query and then reopen upon querying database. You should have/define a pool of connections instead and closing it in Node.js process termination
    process.on(‘SIGINT’, mongo.mongoDisconnect).on(‘SIGTERM’, mongo.mongoDisconnect);
    Refer: Closing a Mongo connection (StackOverflow)
  • Do not use query.remove() for deleting data from the database it’s obsolete, use deleteOne, deleteMany instead.
  • For clearing the session and destroying the browser cookie use:
    req.sessionOptions.maxAge = 0;
    (I use it to logout the user)

Unique web-application on proton pump inhibitors (stomach acid reducing drugs)

For those who wish to see the app immediately click here

At around November 2016, I decided to build a web-app that would encompass scattered data across the web on proton pump inhibitors into one single place with the adding of a unique input form which once populated would yield beneficial data.

Proton pump inhibitors are acid reducing drugs. They are usually taken on an empty stomach to provide maximal benefit to the consumer. Basically, they shut down the little proton pumps in your stomach thereby decreasing stomach acid output. In that way your stomach lining is able to heal more rapidly, and your oesophagus is protected since a low amount of acid in your stomach isn’t able to find its way up to the oesophagus anymore.

The drugs have been released in the late 80’s and brought a revolution in gastro disease treatment. However, around 2014/2015 lot of studies started coming out showing that these drugs could be harmful if taken for a longer period of time.

I myself had stomach issues at age 19 and had been given these drugs to treat my gastritis. Of course, I Googled them and to my surprise found a lot of data. At that time negative studies hadn’t come out yet although there were quite a few people preoccupied with them. I got quickly interested and decided to devote more attention to them.

As already said, studies started coming out swiftly blaming PPIs for sequence of events that they may produce if taken for a prolonged time.

According to the studies PPIs were blamed for: dementia, kidney disease, cardiovascular disease, stomach polyps, clostridium difficile infection, vitamin deficiency, stomach cancer, premature death among others. One gets pretty frightened after hearing all of these elements being associated to them.

Anyway, I decided to get my hands dirty in terms of building a unique software in order to create something beneficial for the gastro disease patient’s community.

The first goal was to collect posts from all around the web and accumulate them into one place.

The posts were collected from various sources, but most of them were retrieved from the following sites:, Peoples Pharmacy, Daily Mail, The Telegraph, Reddit, CBS, The Sun, Crohn’s Disease Forum, Chris Kresser, Barrett’s Wessex, The Healing WELL, The New York Times etc.

The main criteria whether the post was chosen or not was the duration of the therapy. If the duration was specified, the post was analyzed and stored in the database.

Apart from patients expressing their opinions the doctor opinions were also collected. You’d be amazed how much of a non-consensus exists among them. Some of them claim that PPIs are super safe whilst other say that they may yield more damage than steroids. Because of that the input form which I’ve created could solve these problems if a good amount of people decides to give out their data on their therapy.

With the data collected, I generated a statistic page which shows trends in terms of most prevalent conditions, drugs usage, side effects, nutrient deficiency, natural supplements etc.

Likewise, info pages are provided on PPIs as well. This page should answer most of your questions:

As mentioned multiple times in the article the form page: represents the crucial part to demystify if these drugs pose a threat or not. Those of you who are taking PPIs, please fill the form. By doing that you’ll make a great contribution.

If you have any questions concerning the app feel free to ask via mail:



Blockchain average user pros and cons


  • It is secure (referring to blockchain not wallets which are outside the blockchain network)
  • Once you store your data on the blockchain network, it will be there forever.
  • data cannot be deleted/removed, modified, replaced, tampered.
  • Everyone can see your data (it’s public) but no one knows who’s behind it, which person does this data belong to even if they write their name inside it is hard to prove that this person did it. The only way others can learn the transaction is yours is by you telling others that it’s yours or you interacting with them in ways which let others conclude that they may be yours.
  • Since no one knows who’s behind the data, Privacy is therefore guaranteed on the blockchain
  • You have to have a wallet in order to send any data to the blockchain because you have to pay for it
  • If you access/retrieve already existing data you don’t have to pay anything in crypto money
  • Confidential transfer of assets/state to another person,
  • The blockchain database cannot be hacked
  • No one governs over the blockchain database/storage.
  • It’s much easier and less costly to transfer crypto money from one place to another. It’s faster, less expensive and requires no central authority no matter how big the transaction is, fees are very low as well (Ethereum)
  • Blockchain eliminates third parties when making deals. For example you don’t have to go to some company which would just sign some papers and allow you to do something. Instead, someone can deploy an application on the blockchain which would then automatically solve these issues by giving you or not giving you the permission which would had been given from that company previously. In theory all the bureaucracy could get eliminated and put on the blockchain as an application which will automatically solve these problems.
  • People can earn big money on it because of the price which can go up tremendously. Then convert it to Fiat via coinbase or trading.



  • You have to pay crypto-money in order to store data on the blockchain. If you want to store big amounts of data you’ll have to pay even more money whereas on a centralized system you pay once (most often monthly or yearly) and you get unlimited storage. If you wanted to store data, you’d have to pay for the storage (a song of 4MB would be around 7500$ for May 18th 2018, 1ETH=570$)
  • If you lose the access key for your wallet, you’ll never be able to retrieve your money again. You can’t call a centralized company like you do when you lose your bank card and tell them what happened so they may react quickly in order to block your card and disallow potential thieves to spend your money. There is no customer support for the blockchain
  • You have to use a wallet in order to store data on the blockchain (example: MetaMask) that is cumbersome you can’t just interact with the blockchain without such utility.
  • Because of price volatility users are often discouraged to spend money to store big amounts of data on it because one day this crypto could go up and they would probably be disappointed because of it.
  • If you invest in it you can lose a lot of money  if the price drops down or the blockchain project becomes valueless
  • You can lose your money instantly if someone steals your private key. Once the thief has your private key of your wallet/account and you do not react quickly in order to transfer your money to another secure account be prepared to say goodbye to your assets/ crypto money.
  • The blockchain is hard to use, it’s not user friendly. You have to first buy some crypto with Fiat money ($, eur, gbp …) then you would probably transfer it to some wallet since it’s not advisable to keep the money on the same place where you bought (possible hacks may occur), then you have to manage your passwords, plugins…
  • If you are not an IT guy most of the terms won’t be familiar to you, like hashing, miners, proof of work, proof of stake, nonce, hard fork, full node, light node, some protocol names, smart contracts etc. You would have to invest a decent amount of time to comprehend all of the above mentioned. Instead, a centralized system has some nice user interface and you interact with it quickly without worrying about its functionality
  • Governments don’t accept the blockchain regardless of what you’ve read on the news. They don’t offer an exchange service where you could buy dollars, euros using crypto-money. Private companies don’t accept it either. You cannot buy goods, brand new cars, assets with crypto.
  • Scalability is an issue, The problem with the blockchain is that it can only get bigger. Picture it as a huge file which is shared across the network and re evaluated every time a new transactions comes in. Centralized systems don’t have a problem with that.
  • Which problem can the blockchain solve in contrary to centralized internet systems? Only real world problem I can think of is centralized money movement/transfer, lower fees, relatively fast transaction time compared to centralized system transactions (depends on the blockchain) also legal issues can be avoided which may be good or bad.
  • Applications that are currently impossible to be built on top of the blockchain are: Social networks, data storing services, healthcare systems, traffic systems pretty much everything which would require high amounts of data to be stored.



Decentralization is a great thing in general. However, we’ve seen that people don’t really complain having their private data on some unknown addresses like Facebook, Twitter, Google, etc.. Why would they if it has proven to work well: security, customer support, trust…

The problem isn’t privacy. People will use whatever they can under some condition: It has to be simple, useful, reliable, fast and secure. Blockchain doesn’t meet these conditions apart form security and anonymity while on the blockchain.

Another problem with the blockchain is that you have to explain it to someone. It means that you have to convince other people in using it. Convincing often assumes that something isn’t right in the system. People don’t like that, they want to hear what it is good for in one sentence.

Blockchain can acquire critical masses only if it finds a way to solve a problem which the centralized system is not able to solve. Now the question is here, which problem hasn’t been solved by the centralized system? Nevertheless, we’ll have to wait for quite a long time until the blockchain establishes the new, decentralized Internet if it ever does.

People often compare the beginnings of the Internet with the blockchain. They argue how the Internet had to take some time to emerge. That’s true because the infrastructure did not exist and was introduced gradually. The blockchain is the Internet but another architecture of it. Now we come again to the first paragraph of the conclusion, why would someone want to use the same thing with another structure….. Why would someone use Minds social network over stable, big, secure, user-supported, with extremely minor issues Facebook, Twitter, Instagram.

Despite all, why do most of people “like” or so to say talk about the blockchain? They want to make big money fast. Literally you’ll see people on Reddit, Quora and other popular discussion communities asking about the short-term and longterm predictions regarding particular cryptocurrencies. They want to know which is the right one to invest in so they could get “rich” quickly.  This is how they start their journey on the blockchain… Unfortunately there only exists a low percentage of people who really care about decentralization and making the blockchain work smoothly, trying to solve problems, in order for it to become powerful one day and possibly open the gates for mass adoption.


Angular 2 Jasmine unit testing (quick overview)


  • describe: optional, describe the entire unit testing class
  • it: must include it when writing isolated unit test
  • async: tell the test framework to wait until the return promise or observable is completed before treating the test as completed. when all async operations are completed the next test (if exists) is able to start executing
  • beforeEach: for creating new instances for another test to start from the beginning
  • TestBed: creates components instance, configure module, simulate module
  • Access field/variable: fixture.componentInstance.some_variable_name OR if already instantiated then component.some_variable_name
  • detectChanges: only triggered when an property change occurs inside a .ts file
  • configureTestingModule: configures a “fake” module
  • toBe vs toEqual: toBe object(general) equality vs deep equality
  • fixture.whenStable().then(() => {}); executes after all async operations are executed/finished
  • tick() simulates the passage of time until all async operations above are finished. Must go with fakeAsync keyword, otherwise error will appear
  • fixture.whenStable() vs tick();
    They both do the same. tick() is more prudent to use because you have to give it (in the header of the test) a fakeAsync which means that everything is called synchronously inside the test. The code after the tick() method indicates that all code above has executed (async operations above) and that you can now proceed with testing the result of these above async operations.
    Fixture.whenStable() however can give a false positive if async() is omitted in the header of the test. Therefore the test will complete before fixture.whenStable executions.
  • A Spy is a feature of Jasmine which lets you take an existing class, function, object and mock it in such a way that you can control what gets returned from functions.

Configuring Test Module



    let fixture= TestBed.createComponent(AppComponent);
    let element1= fixture.debugElement.query(By.css(".heading")).nativeElement.textContent; //must include the point prefix (.)


  it ("test input innerHTML example", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element2= fixture.debugElement.nativeElement.querySelector(".heading");

input HTML tag

    it ("test input input-value attribute example", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("input");

CSS style

    it ("test input input-value attribute example", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("input");
    it ("test css style", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("h1");
     expect("blue"); // style attribute is the key for testing css

Class property testing

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

beforeEach(() => {
           declarations: [AppComponent]

it('check title class property', async()=> {
  let fixture= TestBed.createComponent(AppComponent);

Service testing

import { TestBed, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component'
import { MyServiceService } from './my-service.service'

beforeEach(() => {
let userServiceStub = {
isLoggedIn: true,
user: { name: 'Test User'}

//simulate module
declarations: [ AppComponent],
providers: [ {provide: MyServiceService, useValue: userServiceStub } ]

it('should test service object property value', inject([MyServiceService], (userService) => {
let fixture=TestBed.createComponent(AppComponent);


Pipe testing

import { TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { AppModule } from './app.module';
import { AppComponent } from './app.component'
import { TryPipe} from './try.pipe'

it ("should check pipe content", async()=>{
    let piping= new TryPipe();  //create an instance of the pipe
    expect(piping.transform("")).toEqual("something"); //transform returns something initially

Directive testing

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { By } from '@angular/platform-browser';
import { FirstOneDirective } from './first-one.directive'
import { NO_ERRORS_SCHEMA }  from '@angular/core';

beforeEach(() => {
    declarations: [ AppComponent, FirstOneDirective ],
    schemas:      [ NO_ERRORS_SCHEMA ]

it('should have skyblue css background, set from the directive', async()=> {
 //checking the code from the directive implementation
  const fixture=TestBed.createComponent(AppComponent);
  const de = fixture.debugElement.query(By.css('.nesto'));
  const bgColor =;

([ngModel]) testing

  it('should pass twice, passes but because of two way data binding ngModel', async(() => {
    const fixture1 = TestBed.createComponent(ChangeRestApiComponent);
     fixture1.whenStable().then(() => {
       let input_val = fixture1.debugElement.query(By.css('#first')).nativeElement;
       input_val.value = 'localhost';

       input_val.dispatchEvent(new Event('input'));


Check something to be false (not to contain a substring)

  it('should not contain full url paths, protocol e.g. http://', () => {
    component.array.forEach((item) => {
        expect(item.url.indexOf('http') === 1).toBe(false);

Checking html CHECKBOX element “checked” attribute

  it('check if checkbox checked attribute changed from default false to true', async() => {
    const input = fixture.debugElement.query(By.css('.className')).nativeElement;
    component.testing = true;

Check value after BUTTON onClick event executes

it('check if on-button (click) event changes the value in the HTML', async() => {
     const div = fixture.debugElement.query(By.css('.clicking')).nativeElement;


Check new INPUT value after change event executes

  it('change input value and check if change occured', async() => {
   const input = fixture.debugElement.query(By.css('.inputlast')).nativeElement;
   component.changeMe = 'changed';

EventHandler(‘click’) testing


Routing testing


Local storage testing


Državna matura riješeni zadaci- matematika A (viša razina), LJETO 2017. god. (postupak)

Napomena: ukoliko ne znate riješiti neki zadatak iz matematike otiđite na: i dobiti ćete rješenje vrlo brzo. Naravno, prije toga morate pokazati pokušaj u rješavanju zadataka. Jedino što morate znati je engl.jezik i po mogućnosti (nije obavezno) malo Latex-a. Latex je jednostavan za naučiti i uči se brzo.


U prilogu se nalaze riješeni zadaci (Matematika A razina) sa državne mature, ljeto 2017. god.
U prvom prilogu se nalazi prvih 15 zadataka dok su u drugom ostali zadaci.

Ukoliko imate kakvih nejasnoća pošaljite mail na

Link na maturu, Matematika A razina 2017, ljeto:


In the attachment below you can find solved problems from the 2017 (summer) math exam, level A.
Students across the country must pass this exam in order to inscribe them-self to a desired faculty.

If you have any question, refer to

Riješeni zadaci s postupkom, 1.dio/solved problems with steps, first part:
MAT A, viša razina, ljeto 2017.god. 1.dio
MAT A, viša razina, ljeto 2017.god. 1.dio

Riješeni zadaci s postupkom, 2.dio/solved problems with steps, second part:

MAT A, viša razina, ljeto 2017.god. 2.dio
MAT A, viša razina, ljeto 2017.god. 2.dio

JS quick tips

Quick theory

– JS uses camel case, lower than uppercase to write a function.
– JavaScript is a loosely typed language (no int, string, bool, char array value types…).
– Declare all variables at the top of the function.
– JavaScript uses the Unicode character set.
– JavaScript Types are Dynamic.
– All functions in JavaScript are objects.
– JavaScript functions parameters are value types.
– In JavaScript, arrays use numbered indexes, they do not support named indexes like in python, object support named indexes.
– In fact, in JavaScript, all functions have access to the scope “above” them.
– JavaScript supports nested functions. Nested functions have access to the scope “above” them. (closures)
– JS doesn’t have pointers (there are pointers but they are called references).
– Closures: when you first call the function then you just invoke the outer function, when you invoke the variable function then you actually call the inner function every time. Basically you need a „double“function call to get the closures to work, no magic.
– The difference between solo functions and and prototype functions is that prototype functions can be applied with a dot (.) where as solo function can not do that.
– Very important: the event queue cannot go into stack-overflow, only the stack can go in such state.
– No, JavaScript objects cannot have duplicate keys. The keys must all be unique. (this is important for example when removing duplicates)
–  Strict keyword– enhances the proper writing of JS. It prevents undeclared variables, it catches some common coding bloopers, throwing exceptions. it prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object). It prevents duplicate properties, eval becomes safer.
– NaN is a Number data type and appears when an arithmetic operation which had to be executed fails. Example: parsing a string to an integer which cannot be an integer when parsed, „abc“ to int.
– JS is asynchronous (non blocking) language
– JS is single threaded, one callstack, no parallel threads (multi-threads) only event loops
– The entire code inside the script block is the main function it doesn’t need a main function explicitly like in C#, Java, C etc.
– The event loop pushes the “result” from the queue to the stack if the stack is empty.

How does JS async work?

The function is pushed to the stack, the API is called for the function, the function executes and goes to the task queue. When the stack is empty the task queue pushes onto the single threaded stack.

Application of bitwise operators in JavaScript

First of all let us revise what bitwise operators are and why you should comprehend them in 2017. Bitwise operators are operators that work on a bit or two bits (comparing them and giving a result based on the comparison) at a time.

AND ( & ) will  be 1 only if both of the bits are 1, otherwise it will be 0.
Example (all combinations): 1&1=1;  1&0=0;  0&1=0;  0&0=0;

OR ( | ) will be 1 if there is a 1 present when comparing two bits,
Example (all combinations): 1|1=1;  1|0=1;  0|1=1;  0|0=0;

XOR ( ^ ) is 1 only if one bit is 1 and the other is 0 no matter the order (1 XOR 0 =1)
(0 XOR 1=1)

NOT ( ~ ) if the bit is 0 it will go to 1 if it is 1 it will go to 0. In this case there is no comparison with other data. If you have an integer, let’s say 5 which is 0101 then the NOT will bring it to 1010.

To see the truth tables go to this website
Practical applications of bitwise operators (real life):
0X1 represents 1 in hexadecimal.

  • We check if the value is odd. If it is, the program returns true it’s not (if it is even) then the program returns false:

(value & 0x1) > 0

Explanation: Let’s say we have a value of 8 and on the other side we have 0x1. We convert them to binary numbers (that’s what the computer only understands at the most bottom level). We write the numbers one below the other and start the calculation from the most right bit to the most left bit (refer to the and operator above)



The result is 0000 which is 0 in denary (decimal ). Zero is not greater than zero so the expression returns false. Which means that the number is even.

JS code:

console.log((8 & 0x1) > 0)
  • Use them for data encryption (encryption is all about bitwise operators)

a = 1903349;
b = 4542345;
c = 5834533;
hash = a ^ b ^ c;

The numbers will be converted to binary and will be hashed (they will be transformed in some boolean XOR equivalent data)


Bitwise operators are rarely used in JavaScript (as far as I’ve seen in 5 years of coding). I suppose interviewers use them for questions for future employees to see how deep the candidate went with their programming knowledge. Still, it is good to know them because once you see them and maybe have to do something with them you will have the basic knowledge in your head and solving the problem in front of you will require less time and frustration.

So, when doing operation with bitwise operators which are nothing else but boolean operations, always have in mind the truth tables which are easy to understand and learn.

My opinion is, try to avoid them because your code looks incomprehensible to others who may in the future maintain your application. The more clearer you are the better for everyone else.