In my previous post, I wrote about Sails.JS ORM which includes model definitions, joins, attributes and such. In this post, I will go over some simple and more advanced queries that will use the previous examples as a basis for our ORM queries. For a more comprehensive list of queries, check out the GitHub documentation for details.

Sails.js uses Waterline out of the box as its ORM (object relational mapper) and it’s basically an object-based way of querying the database. We created the models with a set of attributes, types, etc so it can be used as a 1:1 object representation of table/document in our database. The attributes are used to specify the name of the column/field, length and what type of data it can hold.

For our example, we will be using MongoDB as the database (each database implementation has its own unique of types and querying mechanism) but the ORM allows us to not care about the underlying the technology. Just take note that there might be some slight variance in how certain things are handled.

Basic queries

By default, querying is case-insensitive unless you use the query method. The main keys used to perform queries are where, skip, limit, and sort.
For example, you can use

    .find({ where: { name: 'Dennis' }, sort: 'name desc' });

Or use the short-hand

    .find({ name: 'Dennis'})
    .sort('name desc');

From the previous example, you noticed that you can perform method chainining which performs additional functions on previous result sets. If you wish to omit the key where, the alternative is to use the method chaining approach and that’s just a matter of preference.

Sort, limit, skip

In addition to where, additional query options can be used to in order to further filter down the result set and paginate.
For instance:

    .find({ limit: 10, skip 5 })
    .sort('name desc')

The query limits the returned recoords to 10, skips 5 records, as well as sort it by name. As an alternative, you can also write the same query using the "helper" method approach which can be written as follows.

    .find({ name: 'Dennis' })
    .paginate({ page: 1, limit: 10 })

It queries the "User" column/document that has the name of Dennis and only returns 10 records found on the 1st page.

Advanced queries

In this next section, we’ll go over some of the more advanced features when working against the database records.

Create, update, delete

Creating a new record is as easy as simply passing in the object and calling exec() to perform the insert. The exec takes in a callback that returns an error as the first parameter (if any) and the new record as the second parameter. Always check if an error is not a null and return something meaningful to the user or log if necessary.

    .create({ name: 'Dennis', age: 34 })
    .exec(function(err, user){
        if (err) return res.negotiate(err); // or do something with it

You can also use findOrCreate which performs a check if a record exists or not and performs a create if a record wasn’t found

    .findOrCreate({ name: 'Dennis' })
    .exec(function(err, user){
        // user will be either the existing or new record

Updating is a multi-process which involves looking up the document by its index and performing an update on the returned data. The example below uses the findOneById() which is a useful helper by Waterline to quickly find a single record by id.

    .exec(function(err, user){
        user.name = 'Dennis';
        user.age = 34;

        user.save(function(err, savedUser){

Deleting or "destroying" a record is similar to find where you supply the object criteria of the record(s) that you want deleted. In addition, you need to also use exec to execute the delete and perform the operation. The exec accepts a callback that has 1 parameter on whether the operation succeeded.

    .destroy({ name: 'Dennis' })
        if (err) return res.negotiate(err);

Another useful function that comes with Waterline is the populate method which basically includes additional objects that are associated with the queried document.

For example, let’s say that you have the model User.js and UserFollower.js that has the following definition.

// User.js
module.exports = {
    attributes: {
        name: {
            type: 'string'
        followers: {
            collection: 'UserFollower',
            via: 'user'
// UserFollower.js
module.exports = {
    attributes: {
        // Reference to the user object
        user: {
            model: 'User'

The definition above for the UserFollower essentially includes the ObjectId which is a property that references the id for the user. What this means is that, when you query the User document, you have the option of including any of the other documents that is referenced which includes UserFollower.

If you need to include additional objects as part of the query, you can use populate() to include the object as part of the result set.

var user = User
            .findOne({ id: 1234})

This concludes this post and covers 70-80% of the standard operations and queries that you will encounter in the wild. There’s tons of other Waterline functionalities so be sure to browse through the documentation and experiment with some of the ORM queries that I have mentioned. If you have any suggestions on which topic you’d like to see next (or perhaps a continuation) of this write-up, please feel free to comment or email me. Thanks for reading.

When I got first started with Node.JS about two years ago, I came across Sails.JS and instantly fell in love with it. Two years later, it is still my "go-to" web framework when building a Node.JS application. If you’re not familiar with Sails.JS, it provides a real-time MVC framework on top of Node.JS. It’s basically the ASP.NET MVC for .NET or Rails for Ruby. While it has some pretty nice features out of the box (ie real-time capabilities using websockets, asset pipeline, CLI tools, etc.), the main selling points for me were the built-in conventions and solid, well-thought architecture. For example, /api/Controllers/UserController.js corresponds to the end-point of /api/user that has views of /views/User/index.ejs and so forth. I’ll be discussing some of these nifty features in future posts.

Authorization options in Node.JS

Sails.JS also comes with built-in policies for controlling API permissions which is the authorization piece that goes hand-in-hand with the authentication. When it comes to authentication in Node.JS, Passport is probably the most common middleware option and offers tons of "strategies" for authentication via Facebook, Twitter, etc.

Coming into the Sails.JS world, there are other options as well including Sails-generate-auth which is an abstraction layer/ middleware that utilizes Passport for authentication. There’s also Sails-auth which is also Passport based as well. There’s plenty of options out there so it’s worth considering the pros and cons of each one.


Another great option which I’ve discovered recently which I’ll cover in this post is using what’s called, the "machine-pack". It’s built around the concept of a machine, being that each machine has a well defined purpose and easy to implement (evident of its well written documentation). They also prescribe to a standardized interface which makes it ideal for easy consumption. A set of machine is what constitutes a "machine-pack" which basically combines multiple machines to perform common tasks. A common task can be something like, "authenticate with Facebook" or "send mail with MailGun" and so forth.

A machine-pack that I’d like to share in this post is called machinepack-Facebook which is a machine-pack for authenticating your web application with Facebook. If we explore the machinepack-Facebook bundle itself, it includes a few machines that are stored within the /machines directory which includes get-access-token.js, get-login-url.js, get-longterm-access-token.js and get-user-by-access-token.js.

The concepts in this post are very similar to authentication with Twitter. I’ve looked everywhere on the Internet for implementation specific to machine-packs and couldn’t find one so hopefully this will shed some light on its implementation.

Implementing the machinepack-Facebook

First and foremost, you will need to create an account at Facebook Developers and create an app to get a client/app key and the secret. Once you have those 2 pieces of information, you can create an API by using sails generate api Auth which generates the /api/Auth endpoint. This generates a Model and a Controller API.

Since we’re going to use the key and secret multiple times within our controller, I created /config/appsettings.js which is a config that is exported and available throughout the application. It keeps the code clean and configurable. At the top of the controller before the module.exports = { } is where all the declaration resides at.

The first line basically just requires the machinepack-facebook which will need to be installed via npm install machinepack-facebook --save. The rest are convenience variables to eliminate code repetition.

var Facebook = require('machinepack-facebook');

var callbackUrl = sails.config.appsettings.BASE_URL + '/auth/fbcallback',
    fbClientId = sails.config.appsettings.FACEBOOK_CLIENTID,
    fbSecret = sails.config.appsettings.FACEBOOK_SECRET;

The next chunk of code is for the API function which is the entry point to the authentication process. The 2nd line starts builds the login URL with callback along with the permissions that is being required by your application. The "permissions" below corresponds to a set of permission items that you’d like to access and it’s in an Array format.

I omitted the error callback/handling for simplicity and to make the concepts clear and to the point. I also suggest refactoring the entire Facebook authentication out as a separate service to keep the controller actions clean.

facebook: function (req, res) {
    appId: fbClientId,
    callbackUrl: callbackUrl,
    permissions: [ 'public_profile' ]
    error: function (err){ },

    success: function (result){
      return res.redirect(result);

In the success callback above, the result is a URL that was formed by the Facebook.getLoginUrl() function. The function below is the callback routine where this will go out to Facebooks’s Graph API and asks the user whether it will allow your application to authenticate to Facebook on your behalf. In addition, it also asks for permission(s) such as accessing your profile information, etc.

The getAccessToken() function requires a "code" which is sent back from the previous call to Facebook’s auth service. The "code" verifies that the user has permitted your app’s access request. getAccessToken’s callback then returns a token which can then be used to get the user’s information.

fbcallback: function(req, res){
  var code = req.params.all()['code'];

    appId: fbClientId,
    appSecret: fbSecret,
    code: code,
    callbackUrl: callbackUrl
    error: function (err){ },
    success: function (result){
      var token = result.token;

      // Get information about the Facebook user with the specified access token.
        accessToken: token
        error: function (err){ },

        success: function (result){
          // Result will include the user's profile information for consumption.


In the end, you can then use the id or the email that was sent back by Facebook to lookup in your database on whether the user exists in which, you will need to create a user, then log the user in automatically.
Using Waterline (ORM in Sails.JS), you can do a query such as (this finds a user by either a facebookId or email which are both valid identifiers):

  or: [
    { facebookId: result.id },
    { email: result.email }
}).exec(function(err, user){
  if (user){
    // Update the last logged in date/time stamp and log the user in
  } else {
    // Create a new user and log the user in    

As for the routes, we will need to manually modify the /config/routes.js to tell it to point to the correct API endpoint and handle the type of request properly (GET, POST, PUT, DELETE).

'POST /auth/facebook': 'AuthController.facebook',
'POST /auth/fbcallback/:id': 'AuthController.facebookcallback'

I hope that this helps and and shows how easy it is to use the machine-pack with Sails.JS. Please let me know if you have any questions on the comment below.

I’ve been interested in Node.JS for quite some time now but I haven’t really realized its potential or find a use case. The
extent of my experience was basically creating a quick Express.JS app and see it run in the browser. No formal development whatsoever.
I have come across Sails.JS in the past but that’s when Node was just in its early stages, or at least before I was interested
in the platform. Sails.js coincides with or sits on top of Express.JS using the same MVC pattern as Rails.

I watched the introduction video again for Sails.JS today and was amazed at how powerful it is. The ease at creating a Model, JSON API
end point and by default and Socket IO are the main selling points for me. At the moment, there’s not a whole lot of examples in the
web so I’m going to share a few things that I’ve learned regarding the framework.


According to the Sails.JS documentation, the implementation is very similar to Rails and if you understand how MVC works, it should be easy
to decipher the code in their documentation. The way queries are made is functional in nature which I like but the best part of all these is that
it’s all in JavaScript.

After doing an install via NPM, I began to do some research on what the deployment strategy can be. Since I’m still new to Git and Heroku, I
picked up a few commands that are integral to the Sails.JS and Heroku deployment workflow (setting up Git in any case).

Git commands

Set global GitHub config.

$ git config --global github.user your_user_name

Create new Git repo and commit.

$ cd project_name && git init && git add . && git commit

Get the remote projects.

$ git remote -v

Push latest commit to Heroku.

$ git push heroku master

Heroku commands

Create a project (within the project directory).

$ heroku create or $ heroku create app_name`

Authenticate with Heroku server.

$ heroku login

Add your public key to Heroku.

$ heroku keys:add .ssh/id_rsa.pub

Add key automatically.

$ heroku keys:add

Get all projects in Heroku.

$ heroku list

Open the Heroku app in the browser.

$ heroku open


$ heroku log

Heroku issues on deployment

The two main issues that I’ve encountered while deploying are highlighted below. The application immediately throws a generic error
in which I have to use the command heroku logs to inspect the events.

H14 No web processes running. This is the error that shows when the web dynos is set to 0. Fixing it is a matter of scaling it
to 1 according to the Error Codes page.

$ heroku ps:scale web=1

Immediately after issuing that command, I was faced with another issue in which it complains about a non-existent web type.

No such type as web. This issue took me a while to figure out and after doing some research, I resolved it by adding a "Procfile"
to the root of my Sails JS application with the following code.

web: node app.js

Changing the /config/application.js to a port that Heroku understands (1337 being the default).

port: process.env.PORT || 1337,

After making those changes and issuing a git push heroku master, I had to issue the heroku ps:scale web=1 once again after the changes
has been formally deployed to Heroku.

Pushing to GitHub and Heroku repo simultaneously

Another helpful strategy is instead of issuing a separate git push master to Heroku and
Github is to push it all at once. The .git/config can be modified to do this.

[remote "heroku"]
    url = git@heroku.com:<heroku_repo>.git
    fetch = +refs/heads/*:refs/remotes/heroku/*

[remote "github"]
    url = git@github.com:<github_username>/<github_project>.git
    fetch = +refs/heads/*:refs/remotes/github/*

[remote "all"]
    url = git@github.com:<github_username>/<github_project>.git
    url = git@heroku.com:<heroku_repo>.git
    fetch = +refs/heads/*:refs/remotes/origin/*


After the SSH keys has been added to Heroku and Github (see GitHub and
Heroku documentations on generating a new key), everything is working great.
I also realized that you only need a single key for both accounts.

Many hours after setting up the source control environment later is when learning Sails JS/Node and fun begins.