Fusioncube

The online journey of a technophile, by Steve Brownlee

On Tuesday I did a presentation for the Pittsburgh JavaScript Developers Meetup group about using Node.js with NoSQL – or document based – databases. I chose MongoDB because it’s got great traction and there’s a Node module for it named Mongoose.

Unfortunately, I was on vacation the week before the presentation, so I didn’t get to cover absolutely everything that I wanted to, but I was able to show some great highlights of what can be done with Mongoose. When I first started to look in to it, I was immediately attracted to its syntax and API being very JavaScript friendly.

First things first, though. You can install Mongoose easily by using npm – npm install mongoose.

Then you simply need to include it and create a reference to a local database (if it doesn’t exist, Mongoose will create it for you).

var mongoose = require('mongoose'),
    db = mongoose.connect('mongodb://localhost/test');

Now you’re ready to start working with your database.

One of my favorite things about this system is that you can define, transform, create, and delete all sorts of information without an active database connection. That’s because MongoDB is document based instead of table based.

In the Mongoose API, it all starts with Schemas – something not needed in base MongoDB. A schema is the definition of your document – a rough concept of a table in RDBMS – but instead of all the normalization that goes on in relational systems, documents get embedded in other documents instead of being joined together.

Let’s look at my sample. First, I create an instance of mongoose.Schema and then I create two document schemas – Beer and Type.

var mongoose = require('mongoose'),
    db = mongoose.connect('mongodb://localhost/test'),
    Schema = mongoose.Schema,

    /**
     *  This is the beer type document that is embedded in the beer document
     */
    Type = new Schema({
        name            : String,
        main_ingredient : String
    }),

    /**
     *  This is the beer document which has a sub-document of Type
     */
    Beer = new Schema({
        brand       : String,
        type        : [Type],   // Embed Type into Beer (kinda like join)
        brewery_age : Number,
        rating      : Number
    });

Now that we’ve defined what a beer is, we make a model for it.

BeerModel = mongoose.model('Beer', Beer);

Now that we have a model for beer, we can create instances. Notice that the parameter is simply a JSON object with each property defined… except the Type.

  var Yuengling = new BeerModel({
    brand:'Yuengling',
    brewery_age:105,
    rating: 40
  });

To assign properties to a sub-document you use this syntax.

  Yuengling.type.push({
    name:'Lager',
    main_ingredient:'Malted Barley'
  });

Ok, now that we’ve defined our first beer, let’s save it to the database. No INSERT INTO needed here, it’s absurdly simple. You call the save() method; much more JavaScript friendly syntax. It’s how you would write a save method on any object. Like always in Node – because we never want to block the I/O on our main event loop – you pass an anonymous function that will receive an error message if something went wrong.

Yuengling.save(function(err){
    if (err) { console.log(err); }
  });

Let’s assume, for brevity’s sake – that I’ve added 5 more beers to the database. How would you query it to find beers that have a rating higher than, say, 35? Perhaps the designers of MongoDB live by the K.I.S.S. principle, because you use the find() method. However, the syntax for using operands in the argument list is a bit counter-intuitive.

Let’s find those on our BeerModel.

BeerModel.find({ rating: {$gt: 35} }, function(err, beers) {
   beers.forEach(function(beer){
     console.log(beer);
   });
});

Another feature I really like in Mongoose is you can add methods directly on the schema and then call those methods on any instance. They serve the purpose of a stored procedure in the relational world.

I’m going to modify Beer and create two methods that allow me to increment and decrement the value of it rating property.

    Beer = new Schema({
        brand       : String,
        type        : [Type],   // Embed Type into Beer (kinda like join)
        brewery_age : Number,
        rating      : Number
    }).method('increaseRating', function(){
      this.rating += 1;
      return this.rating;
    }).method('decreaseRating', function(){
      this.rating -= 1;
      return this.rating;
    });

   /**
    * Increase rating of Yuengling
    */
   Yuengling.increaseRating();

   /**
    * Decrese rating of Yuengling
    */
   Yuengling.decreaseRating();

How about a validation trigger? In this case, when you call the save() method with a rating that doesn’t validate, the err argument to the callback function will contain an exception with the message “Rating for beer is not between 10 and 50″.

/**
 * Validate the rating field to be between 10 and 50
 */
Beer.path('rating').validate(function(val){
  return val>10 && val<=50;
}, 'Rating for beer is not between 10 and 50');

These are just scratching the surface of what you can do. At this point in time, the Mongoose API is a bit sparsely documented, but still, if you want to go through the full API you can find everything you need.

You can see my full code on my Github account.

Published on Saturday, Jul 30,2011 | 2 Comments |

This is a special session that is going to run every so often and is meant for JavaScript developers of all ranges, from beginner to seasoned veteran. We’ll take the opportunity discuss all the power, quirks, pros and cons of the JavaScript language starting at “Hello, World” and ending with a dive into the guts of the language to discover why it works the way it does.

Things to be discovered and discussed will include:

  • The Object
  • The Function
  • The Prototype
  • The Arguments
  • The this Scope
  • The Module
  • JSON
  • ECMAScript 5

The host will help moderate the timeline and the discussions, but it is intended to be an interactive session with everyone bringing an equal voice so that we can all learn together.

You are encouraged to bring your own code, and be prepared to share it and discuss it.

Published on Wednesday, Jul 27,2011 | 0 Comments |

I’ll be giving a hands-on demonstration and overview of the ExtJS 4.0 framework. We’ll start from the very basics, in code, to see all of the features on the new version, including:

  • MVC Architecture
  • Charting
  • New data package
  • Infinite scrolling grid

The meeting is currently scheduled to be on July 6th, but I know that’s a big vacation week for people, so if the RSVP level is low, I’ll reschedule for later in the month.

Pittsburgh JavaScript Developers: Building Web Applications With ExtJS 4

Published on Monday, Jun 20,2011 | 0 Comments |

For all the fathers out there who provide for their families – whether it’s financial, emotional, caregiving, motivational, or fun – this Man Card is for you.

Man CardPrint it out, laminate it, tack it on your wall, stick it in your wallet… whatever you like, because you deserve it.

However, make sure you take care of it, because any other man reserves the right to take your Man Card, either provisionally or permanently, if you violate any of the terms & conditions of having a Man Card.

For those who don’t know already, here are they are.

 

Man Card Ownership Terms & Conditions

  1. Mean it.
  2. Own up to it.
  3. Do not wear skinny jeans.
  4. Do not drink anything that is served with an umbrella or cherry.
  5. Only apologize when you screwed up.
  6. If offered a hot towel, or a neck rub, before your hair cut, politely decline.
  7. When it doubt, grill it.
  8. Provide your opinion only when asked.
  9. If you are married, love and respect your spouse without reservation.
  10. If you are married, be your spouse’s best friend.
  11. If you have children, love them and provide for them without reservation.
  12. If you have children, be their father, not their friend.
Published on Friday, Jun 17,2011 | 0 Comments |

“…I feel it in the water, I feel it in the earth, I smell it in the air…”

Like you, I have a wide range of development experience. In the past 20 years, I’ve been a huge fan of Java, C#, Flex (Actionscript), ColdFusion, F#, Ruby and Python. In fact, a few years ago in my last job, myself and some colleagues spent a significant amount of time and effort convincing everyone to migrate to Flex-based applications (they have since decided to migrate yet again to .NET). At the time, it was the right move.

Now I would never suggest such a migration

Feel free to disagree with the following opinion, but from what I’ve been seeing over the past couple of years is…

JavaScript is going to be the virtual machine that drives the next 10 years of software evolution.

Not all software, mind you. I’m talking about the revolution that’s going on in mobile, cross-platform, cloud-based computing and development.

Now, what exactly do I mean by that? JavaScript itself is not a virtual machine, it’s simply a programming syntax, right? Well, that’s true, but remember that the companies writing JavaScript engines are making virtual machines – such as Google’s V8 – that parse and execute JavaScript… and they’re fast. In fact, they are becoming so fast, that JavaScript is slowly, but surely, becoming a ubiquitous language that not only builds the logic and validations of an application, but is now building the actual user interface, and the brains behind it (see server side JavaScript).

We’ll get into that later, but I want to start off with a statement to all the legion .NET, Java, Actionscript, Ruby, Python, {insert language here} developers who look with disdain, or even confusion at JavaScript. You’re missing it. You’re missing what’s going on around you, and for anyone who’s been in software for even a short amount of time, you learn that you adapt or you risk becoming marginalized.

Let’s start off with the trends that I’ve been seeing, and also some nice links that really show off the power of these JavaScript virtual machines. Some are obviously impressive, some are subtly so, but all of them give a taste of what’s coming.

Running An Operating System In The Browser

Start off by checking out Fabrice Bellard’s PC emulator with the Linux 2.6.20 kernel on it. That’s right, an operating system running inside a browser.

Imagining the possibilities of utilizing this kind of tool is exciting. Are you an android developer? Imagine writing your code and then being able to emulate the browser-based version of your program and the mobile version in the browser – side by side.

Imagine having a RAM based file system running in the background behind your web application, and using Web Storage to make the environment and experience different for each user – while never having to communicate with a central server.

How about running a dynamic P2P server inside your browser using WebSockets?

All written with JavaScript. Impossible? We’ll see.

One Language To Rule Them All

Yes, the LOTR references will continue to pile up as this article goes on, just accept it!

Appcelerator Titanium

Some months ago (oh about 6) I stumbled across this tool called Titanium. The only reason that I learned of its existence is because the developers of my favorite tool – Aptana IDE – were acquired by the company Appcelerator. I blithely browsed their web site that day thinking they were just another software development company. However, by the time I was done reading their technology road map, my brain had changed. A light had turned on that hasn’t been shut off since.

JavaScript can be used to design entire applications, and then be compiled into almost every operating system using the standard SDKs! How is this possible? So if I want to write an application that can be deployed on the desktop (Windows, OSX, or Linux) and also be deployed to mobile devices as native applications (Android, iOS, Blackberry), I only need one source code library?

The world is changing, indeed.

Node

What can I say about Node.js that hasn’t been said already? Well, for the uninitiated, Node.js is a program written in C++ that allows you to author server-side services in JavaScript. It is entirely event-driven, on a single thread, and is designed to be a non-blocking I/O framework.

I will not go into any details on it here, but for those who have investigated it, I believe it’s the tip of the iceberg, and for those who have not, well, then you need to spend a couple hours this weekend going down the rabbit hole.

Node.js still has a long way to go (Windows support *cough*), but since its introduction to the world in November of 2009, there are now hundreds of modules written for it that will cover most of your interests and needs.

Most impressive so far is a module called Now.js. It allows you to have real-time communication between your server and your clients with one simple JavaScript file. If any of you have ever tried to implement message queues in the .NET or Java environments, you know how many hoops you have to jump through, how it affects performance and your system architecture. This module is so easy and painless to implement, it almost made me laugh when I first saw it work.

If you’re interested, here’s the original presentation given by Ryan Dahl at the JSConf in 2009.

Code Complete

Given these two tools, you can now write your secure, server logic and the entire customer facing application in one language and have it interpreted to any platform. That’s exciting!

Dumbing Down To JavaScript

I’m sure that’s how many software developers would term the desire to write a program in Java or C# and then run it through a compiler to generate JavaScript! Gasp! How plebian… how absurd!

Yet these companies (little ones named Google and Microsoft, respectively) have written these compilers because there’s a need. First, there’s the Google Web Toolkit for Java and, secondly, there’s Script# for the .NET folks.

Google

I have to give a lot of credit to this evolution to Google. Their brilliant engineers have shown us time after time after time that almost anything you think can’t be done with JavaScript, they have done it. Perfect example. Someone (with an apropos name of Putrid Polecat) commented on Ars Technica story about Windows 8 (see link below) with the following uneducated comment.

Serious applications simply cannot be written in HTML 5 and JavaScript. Continued support for C#/c++/Java must, and therefore will, continue. Can you write adobe illustrator in html5? Blender? AutoCAD? A virtual machine emulator? Device drivers? A compiler?

Cmon guys.

Let’s see…

A virtual machine emulator? Well we covered that.

A compiler? They’re working on it with getToken(). Also, I suppose you could just write your own with JS/CC.

AutoCAD? This one’s probably right with JavaScript in its current state. Its floating point calculations might not be able to support the precision needed by a CAD program. There’s hope for the future, though.

Adobe Illustrator? There’s plenty of online image editors available, but nothing yet as comprehensive as Illustrator. However, with the HTML5 Canvas, I’m betting that it’s coming soon.

Speaking of Google, how about a word processor, or spreadsheet application, or database tool in the browser with JavaScript. Google Docs.

However, I agree with his core point about there always being a need for compiled, strongly typed languages. I just want people to understand that JavaScript is as powerful as any other language, and used properly, can achieve mind-blowing results.

It is not the Gollum of programming languages, but as these tools show, it is the Gandalf. The one language that can somehow bring all the pieces together in order to develop and distribute applications as quickly and as powerfully as possible.

The Big Redmond Machine

Windows 8 APIs are going to be HTML5 and JavaScript? Well, I don’t believe that for a second, and the article even ends saying that there’s more to it and Microsoft will give us more details as time goes by. However, given that a monster, a juggernaut, with the development and marketing power of Microsoft comes out and says that it’s banking on the latest round of W3C specs for HTML, CSS, WebSockets, Web Storage and JavaScript speaks louder than most everything else.

I think this is a great move on their part. Having C#, C++ developers working hand in hand with the JavaScript developers to build the communication and business layer that will feed the presentation layer is probably how it will all end up (viz Appcelerator above). But that’s just a guess.

** Update (09/15/2011) Here’s a great article that describes Metro Plugins (or, more specifically, the lack thereof) in more detail, and some basic info on the Metro style browser that will be in Windows 8 and why JavaScript and HTML are the basis of that experience.

Right Under Our Noses The Whole Time

Raise your hand if you remember the hoopla in the late 90′s about Java being the write once, run anywhere platform that would liberate us all!! Go on, raise your hand, no one will notice. Ok, we all remember, and it failed.

Now, raise your hand again if you remember Adobe, and then Microsoft, saying that compiled, vector-based browser plugins are going to allow us to write once, and run anywhere, and it will liberate us all!! Ok, you don’t need to raise your hand this time, but we all remember (it was just a handful of years ago). It also failed.

Is it possible that, like the gorgeous girl in the movie that no one noticed because she wore glasses and had her hair in a pony tail, the answer was right in front of us and no one saw it? Perhaps Google was the catalyst needed, like the movie bet where the jock dares to turn the nerdy girl into the prom queen, to let us see the true beauty and power of this little toy language written by Brendant Eich – who just so happens to be a native Yinzer (look it up) – way back in 1995.

The most beautiful thing about it is that JavaScript will be the glue that can tie all of the tools together. You can utilize Java programs and C# assemblies from your Node server, integrate a Flash movie or communicate with a Silverlight application in your UI, and then, just for fun, execute a command on your local, browser-based operating system.

Published on Wednesday, Jun 15,2011 | 7 Comments |

About Steve

I am a technologist, and have been ever since 1980 when I got my very first TRS-80 and programmed it to do my math homework. I love to share the gift of technology with others and show them the wonderful things it can do for them, and how they should not fear it, but embrace it.

Latest Tweets

  • Ok... stayed up way too late trying out website designs for my wife's new nonprofit. The kids will be getting me u... — http://t.co/QrKh5iBI
  • Am I the only one who likes Google’s new privacy policy? http://t.co/qwcym5wH
  • All that time wasted learning the .NET framework - Fusioncube - http://t.co/krANoWmg
  • @marcesher libraries like Less only do what you tell them. You can make a mixin to do that, but it doesn't assume anything (which is good)
  • Circus about to start. Girls are so excited they can't stand it!!!! (with Sabrina and Tessa at @BrdgstoneArena) [pic] — http://t.co/PXwi5emj

Subscribe

Entries (RSS)
Comments (RSS)