My new book Full Stack JavaScript (my 4th traditionally-published book) comes with a series of screencast videos for better immersion in a wonderful and mesmerizing world of Node.js, Backbone and MongoDB. It’s a one thing to read through the text and another to follow up with dynamic videos which walk you through the book’s projects.
The videos and the source code are open source, meaning they are publicly available. Therefore, you don’t have to buy a book—you can just watch the 14 videos on YouTube (playlist) and go through the code on GitHub (repository).
MongoUI is a real-time web interface for Node.js and MongoDB written with DerbyJS—a real-time full-stack web framework. It’s a app that can be run locally and on the server. Similarly, you can view and manipulate data in a local or remote database. The MongoUI project is in beta so use caution, and please contribute your feedback.
The HackHall project was written using Backbone.js and Underscore for the front-end app, and Express.js, MongoDB via Mongoose for the back-end REST API server.
After weeks of writing and editing, Azat and his team are happy to announce the release of Express.js Guide: The Most Popular Node.js Framework Manual! The book is very approachable and suitable for beginners. If someone wants to save time searching the web and learn the best practices from the trenches, Express.js Guide is the book that has everything: Express.js API reference, quick start guides, 20+ meticulously explained examples and tutorials on over 270 pages with more than 60 illustrations.
Express.js is a de facto standard of Node.js development and the most popular NPM library as of today! However, as with any framework, sometimes the learning curve is steep. At HackReactor, I often asked the same questions about code organization, authentication, database connections and deployment.
Todo apps are considered to be quintessential in showcasing frameworks akin to famous Todomvc.com for front-end JavaScript frameworks. In this example, we’ll use Jade, forms, LESS, AJAX/XHR and CSRF.
Todo apps are considered to be quintessential in showcasing frameworks akin to famous Todomvc.com for front-end JavaScript frameworks. In this example, we’ll use Jade, forms, LESS, AJAX/XHR and CSRF.
In our Todo app, we’ll intentionally not use Backbone.js or Angular to demonstrate how to build traditional websites with the use of forms and redirects. In addition to that, we’ll explain how to plug-in CSRF and LESS.
Update2: “Mongoskin removed ‘db.collection.id’ and added some actionById methods” from this pull request with this code changes. To use the code in this post, just install an older version of Mongoskin (0.5.0?). The code in the GitHub will work with Mongoskin 1.3.20.
Update2: “Mongoskin removed ‘db.collection.id’ and added some actionById methods” from this pull request with this code changes. To use the code in this post, just install an older version of Mongoskin (0.5.0?)
This tutorial will walk you through writing test using the Mocha and Super Agent libraries and then use them in a test-driven development manner to build a Node.js free JSON REST API server utilizing Express.js framework and Mongoskin library for MongoDB. In this REST API server, we’ll perform create, read, update and delete (CRUD) operations and harness Express.js middleware concept with app.param() and app.use() methods.
This is a release candidate for 1.0 version which is going to be available to public in print. Page count has increase from 151 to 211 pages (PDF), which include the following updates:
More digestible (smaller) code examples with better comments
Express.js middleware section with an example
Express.js + MongoDB REST API server section with an example
Derby section with an example
Grammar and typo fixes
Illustrations
Summaries in the beginning of each chapter
Code examples formatting fixes
This is a release candidate for 1.0 version which is going to be available to public in print. Page count has increase from 151 to 211 pages (PDF), which include the following updates:
More digestible (smaller) code examples with better comments
Express.js middleware section with an example
Express.js + MongoDB REST API server section with an example
If you need in-depth knowledge or references, they are usually one click or one Google search away.
Practical aspect included building multiple versions of the Message Board app:
jQuery + Parse.com JS REST API
Backbone and Parse.com JS SDK
Backbone and Node.js
Backbone and Node.js + MongoDB
The Message Board application has all the foundation of a typical web/mobile application: fetching data, displaying it, submitting new data. Other examples include:
There is a certain magic in ORMs like Mongoose. I learned it the hard way (as usual!), when I was trying to iterate over nested object’s properties…
There is a certain magic in ORMs like Mongoose. I learned it the hard way (as usual!), when I was trying to iterate over nested object’s properties. For example, here is a schema with a nested object features defines like this:
After looking at Google Analytics stats I’ve realized that there is a demand for short Node.js tutorial and quick start guides. This is an introduction to probably the most popular (as of April 2013) Node.js framework Express.js.
Why?
After looking at Google Analytics stats I’ve realized that there is a demand for short Node.js tutorial and quick start guides. This is an introduction to probably the most popular (as of April 2013) Node.js framework Express.js.
mongoui
This app is a start of mongoui project. A phpMyAdmin counterpart for MongoDB written in Node.js. The goal is to provide a module with a nice web admin user interface. It will be something like Parse.com, Firebase.com, MongoHQ or MongoLab has but without trying it to any particular service. Why do we have to type db.users.findOne({'_id':ObjectId('...')}) any time we want to look up the user information? The alternative of MongoHub mac app is nice (and free) but clunky to use and not web based.
REST API app with Express.js and Monk
Ruby enthusiasts like to compare Express to Sinatra framework. It’s similarly flexible in the way how developers can build there apps. Application routes are set up in a similar manner, i.e., app.get('/products/:id', showProduct);. Currently Express.js is at version number 3.1. In addition to Express we’ll use Monk module.
We’ll use Node Package Manager which is usually come with a Node.js installation. If you don’t have it already you can get it at npmjs.org.
Create a new folder and NPM configuration file, package.json, in it with the following content:
Now run npm install to download and install modules into node_module folder. If everything went okay you’ll see bunch of folders in node_modules folders. All the code for our application will be in one file, index.js, to keep it simple stupid:
var mongo = require('mongodb');
var express = require('express');
var monk = require('monk');
var db = monk('localhost:27017/test');
var app = new express();
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
db.driver.admin.listDatabases(function(e,dbs){
res.json(dbs);
});
});
app.get('/collections',function(req,res){
db.driver.collectionNames(function(e,names){
res.json(names);
})
});
app.get('/collections/:name',function(req,res){
var collection = db.get(req.params.name);
collection.find({},{limit:20},function(e,docs){
res.json(docs);
})
});
app.listen(3000)
Let break down the code piece by piece. Module declaration:
var mongo = require('mongodb');
var express = require('express');
var monk = require('monk');
Database and Express application instantiation:
var db = monk('localhost:27017/test');
var app = new express();
Tell Express application to load and server static files (if there any) from public folder:
get() function just takes two parameters: string and function. The string can have slashes and colons, for example product/:id. The function must have two parapemets request and response. Request has all the information like query string parameters, session, headers and response is an object to with we output the results. In this case we do it by calling res.json() function. db.driver.admin.listDatabases() as you might guess give us a list of databases in async manner.
Two other routes are set up in a similar manner with get() function:
Express conveniently supports other HTTP verbs like post and update. In the case of setting up a post route we write this:
app.post('product/:id',function(req,res) {...});
Express also has support for middeware. Middleware is just a request function handler with three parameters: request, response, and next. For example:
app.post('product/:id', authenticateUser, validateProduct, addProduct);
function authenticateUser(req,res, next) {
//check req.session for authentication
next();
}
function validateProduct (req, res, next) {
//validate submitted data
next();
}
function addProduct (req, res) {
//save data to database
}
validateProduct and authenticateProduct are middleware. They are usually put into separate file (or files) in a big projects.
Another way to set up middle ware in Express application is to use use() function. For example earlier we did this for static assets:
app.use(express.static(__dirname + '/public'));
We can also do it for error handlers:
app.use(errorHandler);
Assuming you have mongoDB installed this app will connect to it (localhost:27017) and display collection name and items in collections. To start mongo server:
$ mongod
to run app (keep the mongod terminal window open):
Recently one of our top users complained that their Storify account is unaccessible. We’ve checked the production database and it appeared to be that the account might have been compromised and maliciously deleted by somebody using user’s account credentials. Thanks for a great MongoHQ service we had a backup database in less than 15 minutes.
Recently one of our top users complained that their Storify account was unaccessible. We’ve checked the production database and it appeares to be that the account might have been compromised and maliciously deleted by somebody using user’s account credentials. Thanks to a great MongoHQ service, we had a backup database in less than 15 minutes.
There were two options to proceed with the migration:
Mongo shell script
Node.js program
Because Storify user account deletion involves deletion of all related objects — identities, relationships (followers, subscriptions), likes, stories — we’ve decided to proceed with the latter option. It worked perfectly, and here is a simplified version which you can use as a boilerplate for MongoDB migration (also at gist.github.com/4516139).
Let’s load all the modules we need: Monk, Progress, Async, and MongoDB:
var async = require('async');
var ProgressBar = require('progress');
var monk = require('monk');
var ObjectId=require('mongodb').ObjectID;
By the way, made by LeanBoost, Monk is a tiny layer that provides simple yet substantial usability improvements for MongoDB usage within Node.JS.
Monk takes connection string in the following format:
username:password@dbhost:port/database
So we can create the following objects:
var dest = monk('localhost:27017/storify_localhost');
var backup = monk('localhost:27017/storify_backup');
We need to know the object ID which we want to restore:
var userId = ObjectId(YOUR-OBJECT-ID);
This is a handy restore function which we can reuse to restore objects from related collections by specifying query (for more on MongoDB queries go to post Querying 20M-Record MongoDB Collection. To call it, just pass a name of the collection as a string, e.g., "stories" and a query which associates objects from this collection with your main object, e.g., {userId:user.id}. The progress bar is needed to show us nice visuals in the terminal.
var restore = function(collection, query, callback){
console.info('restoring from ' + collection);
var q = query;
backup.get(collection).count(q, function(e, n) {
console.log('found '+n+' '+collection);
if (e) console.error(e);
var bar = new ProgressBar('[:bar] :current/:total :percent :etas', { total: n-1, width: 40 })
var tick = function(e) {
if (e) {
console.error(e);
bar.tick();
}
else {
bar.tick();
}
if (bar.complete) {
console.log();
console.log('restoring '+collection+' is completed');
callback();
}
};
if (n>0){
console.log('adding '+ n+ ' '+collection);
backup.get(collection).find(q, { stream: true }).each(function(element) {
dest.get(collection).insert(element, tick);
});
} else {
callback();
}
});
}
Now we can use async to call the restore function mentioned above:
Storify saves a lot of meta data about social elements: tweets, Facebook status updates, blog posts, news articles, etc. MongoDB is great for storing such unstructured data but last week I had to fix some inconsistency in 20-million-record Elements collection.
Storify saves a lot of meta data about social elements: tweets, Facebook status updates, blog posts, news articles, etc. MongoDB is great for storing such unstructured data but last week I had to fix some inconsistency in 20-million-record Elements collection.
The script was simple: find elements, see if there are no dependencies, delete orphan elements, neveretheless it was timing out or just becoming unresponsive. After a few hours of running different modifications I came up with the working solution.
Here are some of the suggestions when dealing with big collections on Node.js + MongoDB stack:
Befriend Shell
Interactive shell, or mongo, is a good place to start. To launch it, just type mongo in your terminal window:
$ mongo
Assuming you have correct paths set-up during your MongoDB installation, the command will start the shell and present angle brace.
Separate your query into a few scripts with smaller queries. You can output each script to a file (as JSON or CSV) and then look at the output and see if your script is doing what it is actually supposed to do.
To execute JavaScript file (fix.js) and output results into another file (fix.txt) instead of the screen, use:
$ mongo fix.js > fix.txt --shell
or
$ mongo --quiet fix.js > fix.txt --shell
Check count()
Simply run count() to see the number of elements in the collection:
db.collection.count();
or a cursor:
db.collection.find({…}).count();
Use limit()
You can apply limit() function to your cursor without modifying anything else in a script to test the output without spending too much time waiting for the whole result.
For example:
db.find({…}).limit(10).forEach(function() {…});
or
db.find({…}).limit(1).forEach(function() {…});
is better than using:
db.findOne({…})
because findOne() returns single document while find() and limit() still returns a cursor.
Hit Index
hint() index will allow you to manually use particular index:
Rapid Prototyping with JS is a hands-on book which introduces you to rapid software prototyping using the latest cutting-edge web and mobile technologies including NodeJS, MongoDB, BackboneJS, Twitter Bootstrap, LESS, jQuery, Parse.com, Heroku and others.
The book has 84 pages (in PDF format) or 13,616 words to be precise, step-by-step set-up, best practice advices, web development overview, 11 code examples (also available ready-to-go in GitHub repository azat-co/rpjs), flexible pricing ($9.99–19.99).
LeanPub platform allows readers to receive infinite future updates (current version of the book is 0.3) and read the book in the most popular digital formats: PDF, ePub/iPad, MOBI/Kindle. The PDF version has footnote links which make it suitable for printing.
Rapid Prototyping with JS is being successfully used at StartupMonthly as a training manual. Here are some of our trainees’ testimonials:
“Thanks a lot to all and special thanks to Azat and Yuri. I enjoyed it a lot and felt motivated to work hard to know these technologies.” — Shelly Arora
“Thanks for putting this workshop together this weekend… what we did with Bootstrap + Parse was really quick & awesome.” — Mariya Yao
“Thanks Yuri and all of you folks. It was a great session – very educative, and it certainly helped me brush up on my Javascript skills. Look forward to seeing/working with you in the future.” — Sam Sur
Who This Book is For
The book is designed for advanced-beginner and intermediate level web and mobile developers: somebody who has just started programming and somebody who is an expert in other languages like Ruby on Rails, PHP, and Java and wants to learn JavaScript and Node.js.
Rapid Prototyping with JS, as you can tell from the name, is about taking your idea to a functional prototype in the form of a web or a mobile application as fast as possible. This thinking adheres to the Lean Startup methodology. Therefore, this book would be more valuable to startup founders, but big companies’ employees might also find it useful, especially if they plan to add new skills to their resume.
Prerequisite
Mac OS X or UNIX/Linux systems are highly recommended for this book’s examples and for web development in general, although it’s still possible to hack your way on a Windows-based system.
Contents
Acknowledgment
Introduction
Who This Book is For
Prerequisite
What to Expect
Notation
Web Basics: Hyper Text Markup Language, Cascading Style Sheets, JavaScript
Traditional Computer Science education sucks big time when it comes to modern agile technologies like Ruby on Rails, Django, NodeJS, and NoSQL databases. Last time I checked, the maximum that was offered were classes in Web Design I, Web Design II and Photoshop Basics. WTF?! Don’t get me wrong. I have Master’s degree in Information Systems Technology and value fundamentals, but I was never taught anything up-to-date. There was some ASP, some C++, some SQL, but most of my learning I had to do on my own. Sure there are tons information online and in books, but not everybody has time, dedication, focus and self-discipline to master a new technical skill this way. Reading a book or watching a screencast is just not enough. The best learning comes from 25% books, 25% peer-to-peer communication and discussion, 25% student-to-teacher relationship; the last 25% is the time and practice on your own.
I saw a huge need for effective technical trainings and decided to validate my idea. I already had plenty of teaching experience from college years, during which I wrote my first textbook, had it published on a curriculum for my classmates a year later, and from teaching yoga classes. I needed a pilot class, so I approached startup accelerator and fund, StartupMonthly, and offered to develop and teach the “Rapid Prototyping with JavaScript and NodeJS” training.
I chose JavaScript and NodeJS because students will be able to use the same language both for front-end and back-end development. Their brains don’t have to switch thus saving time and speeding the learning process. NodeJS is becoming more and more popular due to its real-time support and I’m very passionate about this technology. The training runs over a long weekend, starting on Friday night with an optional Q&A session on setting up your environment. Then, we have two full days on Saturday and Sunday, making the course 16 hours total. This way, people who have full time jobs don’t have to take time off to attend. The class is very hands-on and, as much as possible, inline with the principles of Flipped Teaching.
The goal was not to make a profit. So we priced the training very aggressively twice or thrice lower than the market price of our competitors in order to attract students. The results were amazing! The goal was to sell at least 10 seats and we had 15 people in our first class! Big thanks to Yuri Rabinovich, killer StartupMonthly team and its vast network of people interested in technology :)
Then the hard work began. In a true spirit of lean startup methodology (hey, this is what we teach, right?) the manual had only a bare minimum of information and was tailored towards intermediate web and JavaScript developers. The majority was doing well, but I couldn’t say that for everyone. This was a good feedback for me, and helped to improve the manual by including many simple steps and additional terminal commands for deployment and Git.
Overall, students were tired, but happy with the number of new technologies they’ve tried. It was sort of a Chinese Buffet of Programming. You don’t have to try everything, you only pick what you want and indulge in it :) Here is the list of topics to give you an idea:
Building your own idea/prototype and presenting it. Deploying it to cloud services.
Practicing Paired Programming and Test-Driven Development techniques.
By the end of the weekend, we had 3 teams with 2 to 3 people in each. The teams built or started to build applications using their own ideas. One of them was a remake of Reddit with better UX/UI and the other was a service for angry ex-girlfriends to post (mostly negative I suspect) feedbacks on their ex-boyfriends :)
Here are some testimonials from the students:
“Thanks Yuri and all of you folks. It was a great session – very educative, and it certainly helped me brush up on my Javascript skills. Look forward to seeing/working with you in the future” – Sam Sur.
“Thanks for putting this workshop together this weekend… what we did with Bootstrap + Parse was really quick & awesome” – Mariya Yao.
“Thanks a lot to all and special thanks to Azat and Yuri.
I enjoyed it a lot and felt motivated to work hard to know these technologies” – Shelly Arora.
Next weekend, August 10–12 2012, I’m teaching the second class of “Rapid Prototyping with JavaScript and NodeJS”. I’m exited to share my experience and passion with another 10–20 smart people and make a small dent in technical education!