How to use mongoose with MongoDB in Node.js

Here is the example how to start simple project with usage of Mongoose for MongoDB on Node.js and mongoDB hosted on mongolab.

First of all you need to correct package.json file in your project to something like this

{
    "name": "rent",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node app"
    },
    "dependencies": {
        "express": "3.0.2",
        "jade": "*",
        "log4js": "0.5.6",
        "mongoose" : "3.5.4",
        "moment" : "1.7.2",
        "mongoose-pureautoinc": "*"
    }
}

Make sure that you have added mongoose package, other stuff just for example
run
Mikitas-MacBook-Air-2:test nik$ sudo npm install
or just “npm install” (for windows or if you configured permissions)
You can also use “npm install mongoose” to install it.

Let’s create mongoDB “model”. So somewhere in your DAL try this code:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema
    , ObjectId = Schema.ObjectId;
 
// let's create scheme for some random stuff:
var postSchema = new Schema({
    _id: ObjectId,
    thumbnail: String,
    whenCreated: Date,
    whenUpdated: Date,
    comments: [{
            author: {
                authorId: ObjectId, 
                name: String, 
                thumbnail: String
            }, 
            date: String, 
            text: String
    }],
    rating: Number,
    isApproved: Boolean,
    text: String
}, { collection: 'post'});
 
// and let's register this scheme as a model and make global for this module
module.exports = mongoose.model('Post', postSchema);

Now we can include this file:

var Post = require('../DAL/models/Post');

And use it for example to get all items from collections

exports.getPosts = function (callback){
	return Post.find({/* query */}, function (err, docs){
		if (!err) { 
			callback(docs);
		}
		else { 
			throw err;
		}
	});
}

Note: that the operation is async and you will get result only in callback
please check this mongo docs out

Or we can insert new item into collection:

exports.addPost = function (){
    var post = new Post();
    post.rating = 5.89;
    post.text = "Here is one more post to my blog on MikitaManko.com/blog/"; 
    post.isApproved = true;
    // other fields
    post.save();
}

Here is one more link on mongo docs

Finally, to use this “DAL” methods we need to create connection to DB.
You can use https://mongolab.com/ service to host your DB for free (until your DB is less then 500 mb).
After you created new BD on mongolab you can create connection with the following way:

var mongoose = require('mongoose');
 
mongoose.connect('mongodb://<your login>:<your password>@<your id>.mongolab.com:61777/<database name>');
// here you can call methods described above

That’s it, just several lines of code, some clicks and you have MondoDB database already hosted in web.
Perfect solution for Hackathons, fast tests and startups.

By the way, you can host you Node.js code on https://www.heroku.com/ service also for free (until it exceeds some limitation, for details check heroku website out)

Social Share Toolbar

JavaScript Quiz

Some awkward questions that may be asked on the interview or during the JavaScript lectures.

Type conversion

var a = 1 + '2' + 3;

Answer:

“123” because 1 will be converted to string and “1” + “2” is strings concatenation operation

var b = +(1 + 2 + '3' + 4) + 5;

Answer:

“339” similar situation, firstly 1 and 2 will be summarized as numbers, and the result will be 3. Then conversion to string and will be concatenated “34”. After that the string “334” will be converted to the number, because of plus operator. Afterwards to the number 334 will be added 5, so the result is 339

var c = '4' - 3;

Answer:

1, because the second operand is integer, so the first one will be converted to number 4

Context

if (!("a" in window)) {
    var a = 1;
}
alert(a);

Answer:

undefined. Because:

1) all global variables are properties of window. Writing var a = 1 is functionally equivalent to writing window.a = 1

2) all variable declarations are hoisted to the top of the containing scope.

variables vs functions hoisting

var a = 1,
b = function a(x) {
    x && a(--x);
};
alert(a);

Answer:

1
Because:
1) variable declaration hoisting (where declaration is “var a;” and initialization is “a = 1;”)
2) All function declarations are hoisted to the top of the containing scope along with variable declarations. Function expressions are not hoisted.
where declaration is “function functionName(arg1, arg2) { /* function declaration – will be hoisted */ }”
and expression is “var functionName = function (arg1, arg2) {/* function expression */};”
Problem? Just read ECMA 5 (13.0)
3) function declarations override variable declarations but not variable initializations. The variable initialization overrides the function declaration.
So
function value() {
return 1;
}
var value;
alert(typeof value); //”function”

and

function value() {
return 1;
}
var value = 1;
alert(typeof value); //”number”

one more variables vs functions

function a(x) {
    return x * 2;
}
var a;
alert(a);

Answer:

the answer is the body of function a:
function a(x) {
return x * 2;
}
Ha-ha, function declarations override variable declarations unless there’s an initialization.
So, for this case
function a(x) {
return x * 2;
}
var a = 1;
alert(a);

we gonna get – 1
Pretty cool, yep?)

arguments

function b(x, y, a) {
    arguments[2] = 10;
    alert(a);
}
b(1, 2, 3);

Answer:

10
Because each entry in the arguments object is a duplicate of each named argument.

context

function a() {
    alert(this);
}
a.call(null);

Answer:

[object Window]
Reasons are:
1) When a method is called on an object, this points to the object on which the method resides.
2) If thisArg is null or undefined, the called function is passed the global object as the this value. Otherwise, the called function is passed ToObject(thisArg) as the this value. (in this case it will be window)
So, the code above could be converted to:
function a() {
alert(this);
}
a.call(window);

Or, even to

alert(window);

typeof

typeof typeof (null)

Answer:

“string”
Firstly typeof operator always returns a string value (in this case, it returns “object” for typeof(null)). null is type object and undefined is type undefined.
Whenever you have typeof typeof, the result is always “string”.

toString

100['toString']['length']

Answer:

1
1) Numbers end up wrapped by the Number type when you use them, and the Number type has a toString()
2) The length property of a function indicates how many names arguments are expected. The toString()methods accepts one argument, which is the radix in which to output the string representation of the number (for example toString(2) outputs the binary representation of the number as a string and toString(16) outputs the hexadecimal representation of the number as a string).

Comma

var a = (1, 5 - 1) * 2;

Answer:

8
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand (not the second, the last one)
Some extra examples:
a = ‘hello’, ‘world’; //’world’
a = 1, 2 + 3, 4 – 1; //3

One more comma

var x = 10;
var foo = {
    x: 20,
    bar: function () {
        var x = 30;
        return this.x;
    }
};
console.log(
  foo.bar(), // 1 case
  (foo.bar)(), // 2 case
  (foo.bar = foo.bar)(), // 3 case
  (foo.bar, foo.bar)() // 4 case
);

Answer:

1 case – 20
2 case – 20
3 case – 10
4 case – 10
Brain damage… ?
That’s pretty simple in case if you bear in mind that foo.bar in this part of the code represents a pointer to the function, and the comma operator takes on the value of that function before being called. 
Also, for case 3 function location gonna be changed to window.

Arguments

function f(x, y) {
    x = 10;
    console.log(arguments[0],
        arguments[1]);
}
f();

Answer:

undefined undefined
The arguments object and the named argument do not share memory space. When a change is made to arguments, that value is copied to the named argument. It doesn’t work the other way.
A named argument is no more special than a local variable, and so changing its value doesn’t affect the arguments object.

P.S. If you were able to solve all these quizzes, my congratulation you are cool enough! Just mail me to gmail(doggy)MikitaManko.com and I will recommend you if needed =)

Social Share Toolbar

JavaScript design patterns

Here are the most common JavaScript solutions that should be used in production code, everybody calls this list as JavaScript Design Patterns, but I think that it’s just good code’s rules. By the way, here they are:

immediate function pattern
purpose: to wrap some code in the context. Let us reduce polluting of the global context

(function () {
    alert('Hello');
} ());

purpose: the same solution, but with saving of results

var someVar = (function () {
    return 'result';
} ());

purpose: here is the real world example, it allows to use $ symbol as a jQuery in one context and as a Prototype library in another context without polluting of the global context. This solution must be used with any external library.

(function ($) {
    $(".menuOverlay").show();
} (jQuery || $));

note: Immediate function wrapped in parens, because:

  • Without parens it would be interpreted as function declaration (not expression) which is syntax error
  • Function expression can not start with word “function”

What is a Function Declaration?

function foo() {
    return 'result';
}

What is a Function Expression?

var bar = function () {
    return 'result';
}

immediate object initialization pattern
purpose: This pattern is mainly suitable for one-off tasks, and there’s no access to the object after the init() has completed. If you want to keep a reference to the object after it is done, you can easily achieve this by adding return this; at the end of init().

({
    width: 100,
    height: 200,
 
    getArea: function () {
        return this.width * this.height;
    },
    init: function () {
        console.log(this.getArea());
        //other init code
    }
}).init();

memoization pattern
purpose: the main goal is performance optimization. It’s real deal to save pre-calculated results. E.g. for Fibonacci numbers, juat implement solution with and without this pattern and you will see the difference.

function average(x, y) {
    var key = x + '_' + y;
    if (!average.cache.hasOwnProperty(key)) {
        average.cache[key] = (x + y) / 2;
    }
    return average.cache[key];
}
average.cache = {};
 
average(10, 20); //calculate
average(10, 20); //take from cache
average(20, 10); //calculate

Loop closure pattern
purpose: to eliminate “cycle f**k ups”, I mean the situation when you use cycle iterator variable in closure and you expect 1, 2, 3 .. values in different functions, but you have always last value in all.

var arr = ['one', 'two', 'three'];
 
for (var i = 0, len = arr.length; i < len; i++) {
    (function (i, d) {
        //access index and data
        console.log(i + ') ' + d);
    } (i, arr[i]));
}

The same code with jQuery

var arr = ['one', 'two', 'three'];
 
$.each(arr, function (i, d) {
    console.log(i + ') ' + d);
});

implementation is similar to

var forEach = function (d, f) {
    for (var i = 0, l = d.length; i < l; i++) {
        f(i, d[i]);
    }
};

Private member
purpose: restrict access to private members

function Semaphore(start) {
    var value = start; //private variable
 
    //private method
    function resetValue(){
        value = 0;
    }
 
    return {
        enter: function () {
            value++;
        },
        leave: function () {
            value--;
        },
        getValue: function(){
            return value;
        }
    };
}
 
var sem = new Semaphore(0);
sem.enter();
sem.enter();
Assert(sem.getValue()==2);
sem.leave()
Assert(sem.getValue()==1);
Assert(!sem.hasOwnProperty('resetValue'));//could not access private method
Assert(!sem.hasOwnProperty('value')); //could not access private variable

Optional parameter pattern

purpose: add ability to specify optional parameters
When function has a lot of parameters

function Car(name, model, color, number, wheelsRadius, year, autoTransmission) {
    //do something with all parameters
    return 'result';
}

This is bad code, because all parameters must be set when instantiating (even optional parameters)
e.g.

var myCar = new Car('Honda', 'civic', 'red', null, null, 2004, false);

also the order of the parameters is fixed and it’s hella hard to add one more parameter, when this is boilerplate code

So, the decision is to convert list of parameters to one object…

function Car(settings) {
    var defaultSettings = {
        name: 'Unknown',
        model: null,
        autoTransmission: false,
        wheelsRadius: 16
    };
 
    this.settings = $.extend({}, defaultSettings, settings);
 
    return this.settings;
}
 
var myCar = new Car({ name: 'Honda', model: 'civic', color: 'red', year: '2004', autoTransmission: true });

Note: if function has more then 3 parameters it must be converted to the function with one object-parameter.

Namespace pattern
purpose: reduce pollution of global context and simplify code organisation.
Here is Bad practice (pollute global scope):

function Init() { };
function Run() { };
var state = 1;
var module1 = {};
module1.data = [1, 2, 3];
var module2 = {};

Here is Better practice, but not good enough:

var MYAPP = {};//only one global object;
MYAPP.Init = function () { };
MYAPP.Run = function () { };
MYAPP.state = 1;
MYAPP.module1 = {};
MYAPP.module1.data = [1, 2, 3];
MYAPP.module2 = {};

Why not good enough? Because if you have a lot of modules, you will do something like:

if (typeof MYAPP === "undefined") {var MYAPP = {};}
if (typeof MYAPP.modules === "undefined") {var MYAPP.modules = {};}

Here is the Namespace pattern (read it carefully, it’s pretty interesting):

var MYAPP = MYAPP || {};
MYAPP.namespace = function (nameSpace) {
    var parts = nameSpace.split("."),
        parent = MYAPP,
        i;
 
    if (parts[0] === "MYAPP") { // strip redundant leading global
        parts = parts.slice(1);
    }
    for (i = 0; i < parts.length; i++) {
        // create a property if it doesn't exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

To create new (or get already existing) namespace you need to write:

var moduleCar = MYAPP.namespace("MYAPP.modules.moduleCar");

Module pattern
purpose: Javascript doesn’t have special syntax for packages, but with help of “namespace” and “immediate function” patterns we can achieve this:

MYAPP.namespace("MYAPP.utilities.stack");
MYAPP.utilities.stack = (function () {
    var stack = [];
 
    function push(value) {
        stack.push(value);
    }
 
    function pop() {
        return stack.pop();
    }
 
    function somePrivateMethod() {
        stack = [];
    }
 
    return { // public API
        push: push,
        pop: pop
    };
} ());

Chaining pattern
purpose: add ability to use similar cool stuff as it possible with jQuery (I mean this chaining – $(‘.container’).html(markup).show() …)

var calculator = (function () {
    var value;
    return {
        init: function (startValue) {
            value = startValue;
            return this;
        },
        add: function (val) {
            value += val;
            return this;
        },
        mul: function (val) {
            value *= val;
            return this;
        },
        result: function () {
            return value;
        }
    };
} ());
 
console.log(calculator.init(2).add(2).mul(2).result());//8

P.S. It’s pretty obvious, but you can use different combination of these patterns to achieve your goal.

Social Share Toolbar

slides from frontendConf

My slides from frontendconf.by – https://speakerdeck.com/mikitamanko/high-load-javascript-framework-without-inheritance-1

video with presentation:
part 1 – http://video.yandex.by/users/fdconf/view/22/ (Russian)
part 2 – http://video.yandex.by/users/fdconf/view/21/ (Russian)

Social Share Toolbar

Link folder into Visual Studio Project

As far as we all might know, Visual Studio allows to add existing file as a link.

file as a link

But sometimes it could be pretty useful to add whole folder as a link. As a result I want to change\add\remove files in one directory and to observe the same changes in the other project. The first thing that came up to my mind was hard link (yeah it’s strange).
But I was sure enough that I can make it by adding several lines to .csproj file. Here they are:

<Compile Include="..\..\..\OtherProject\CommonFolder\*.cs">
     <Link>CommonFolder\%(FileName)</Link>
</Compile>

and here is the example ho to add files as a content (one file)

    <Content Include="..\WebClient\index.html">
      <Link>www\index.html</Link>
    </Content>

and the whole directory

    <Content Include="..\WebClient\Pages\*.html">
      <Link>www\Pages\%(FileName)</Link>
    </Content>

Just to clarify – all these changes I’ve added to e.g. MyProject.csproj file.

Social Share Toolbar

HOW TO run Window Phone 8 emulator on parallels on mac

That awkward moment, when you want to use you windows on parallels for Windows Phone 8 development (and don’t want to install windows via bootcamp).

Shortly some helpful point:

  • first of all ensure that you have Parallels desktop 8 for mac (it’s really important to have 8 version, if not – just update it by the install 8 version)
  • go to parallels settings – “Optimisation” and check “Nested virtualisation enabled”
  • go to parallels hardware settings and ensure that you have configured ONE cpu and at least 4GB of ram (may be it will work with 2 GB I don’t know). It is really important to set only 1 CPU
  • make sure that you have installed parallels tools on your windows 8 (yep windows 8 on your parallels)
  • ensure that you have windows 8 pro edition (I had windows 8 N, then updated to windows 8 Pro N), if not – update it. Open My Computer, right click – Properties. Check your windows version, if it’s not pro, click “get more features” or something like this. You should enter serial key and wait until windows will install all cool features. (Serial keys could be taken from your msdn premium subscribtion account, if you have one, just click “get key” near the windows 8 pro, on pro N edition, copy-paste it to the windows updating window and follow the white rabbit)
  • Now you have windows 8 pro edition, cool! Find on start screen “Hyper-v manager”, configure your device emulator, and set ONE cpu, only ONE, seriously 1.
  • Now you could try to run you project in VS 2012 on device. In case if you will have an error with CPU counts, something like “…this can happen when the virtual processor or socket count…” open parallels settings and ensure that you configured one cpu, and open hyper-v manager and look at settings for device emulator you trying to run – open it’s settings and set cpu count to one
  • That was the small manual how to run windows 8 emulator on parallels for mac, or how to start hyper-v on parallels for mac.

    Social Share Toolbar

    My thoughts about future of pointing devices

    It’s cool to be on the cutting edge of new technologies, and it is cool to invent or even just try something new.
    All we have been inspired by sci-fi films with “future-rised” interfaces.
    And all we have been inspired by google glasses, it’s hella cool device

    But STOP, what’s going on with PC/Laptop’s pointing devices?
    You know, I mean “leap motion”, “mycestro” and other similar devices that reinvented kinect for PC/Laptop.
    For example here is one more DIY motion device – http://www.youtube.com/watch?feature=player_embedded&v=U180f3XG20o. It is great presentation, it is interesting device, but thats it. I don’t believe that lazy people will waving their hand the whole day. It’s too hard, believe me. May be in the near future laptops and other devices will have second web-camera and somebody gonna use “leap motion\kinect like” gestures to list presentation’s slides. But I’m sure that nobody will use it in daily work, just because it’s too hard.
    I believe that mouse/trackpad device will be replaced by eye-tracking mechanism, or by the mind-PC interface, but not with the kinect like toys. It is really funny, but I think that this is totally useless

    Social Share Toolbar

    Some thoughts about html5 by Christian Heilmann

    http://www.youtube.com/watch?v=r7xnKSPWTjo – it is really cool presentation for anyone who cares about the web (by Christian Heilmann http://christianheilmann.com/)

    P.S. just put here some interesting tools:

    Social Share Toolbar

    You can’t create a button

    Here is very interesting article http://www.nczonline.net/blog/2013/01/29/you-cant-create-a-button/ by Nicholas C. Zakas. Most excited point is about replacing default browser’s elements (such as checkbox, button, etc) with simple div and span elements. This patters is actively used by google, and as it was described in article it’s a mistake. Details are in the article

    Social Share Toolbar

    Hackathon – first experience, helpful tips

    I have heard about hackathon events in Facebook and Google and about all this hackers culture, that could pass for something for nerds only. I have even experience as an organiser of company’s internal hackathon event. And finally I took part in hackathon
    in person with excellent team, and this is beyond words how cool it was. It is the great challenge to create something new, something completely ready for demo, only for 24 hours.
    In hackathon you can participate in all phases of the software’s lifecycle only for 24 hours.

    Some tips that I discovered for myself:

  • find your team
  • find something like whiteboard and marker
  • come up with some ideas
  • finally choose idea that your team will implement
  • work out the details of minimum working version – all features and improvements MUST be hold over till minimum version will be ready
  • DON’T try to do everything right, I’m about good architecture design and universalism. This is very important point that may save your time. If you can not do something fast enough – hack it. If you have a problem – hack it. This is HACKathon. The result you will show on the demo, so you should hack enough to prepare application for the demo
  • Think about what will take place at the demo
  • It’s obviously, but divide functionality into tasks.
  • It is necessary to monitor progress of each team member. For example we have been working by agile methodology. We used 45 minutes sprints. And after each sprint we got stand up meeting. Then we must rest – 10-20 minutes we had been playing in kicker/kinect/eat something/etc
  • rest is very important point – don’t forget about it
  • Here is our result – https://github.com/DjComandos/MobileRockBand

    Looking forward to the next Hackathon.

    Social Share Toolbar