« Back to home

Introduction to Sails.JS Models and ORM, part 1

I have been working with Sails.JS for a little while now and would like to share a bit of information on how to use the Models and Waterline/ORM (Object Relational Mapper) when working with your database. An ORM is basically an API to access your database and perform queries against it. Waterline as an ORM has built-in adapters that allows you to use MS SQL Server, MongoDB, Redis among a host of others. It simplifies the process of working with a database since you're using the same API regardless of what database you're using (see Waterline on GitHub to see if there's an adapter available for your database).

You can use Waterline in any flavor of Node.JS but in this post, I'll be discussing Waterline in the context of Sails.JS although the implementation and concepts are pretty much the same. The adapter should not be relevant in most cases but certain databases have other functionalities that other databases doesn't so this is something that you need to be aware of. A simple example of this would be if you're using a relational database such as SQL Server that allows you to add precision or size to the column property (ie. nvarchar(128).

{
    name: { 
        type: 'string',
        size: 128
    }
}

To keep things simple, I'm also going to use from the NoSQL perspective as the context of the post although like I have mentioned, the examples will handle most cases and scenarios.

Models

A model essentially describes a table/collection in your database and makes up the definition of properties or attributes and what it can contain. Model usually maps to your database table or collection. By having defined models, you are adding constraints on what properties/fields that can be saved.

Each model consists of one or more attributes which can be of type string, int, etc. (see more below). A model is synonymous with Collection as each collection can contain many Models.

Globals

All models assuming that they're stored (by convention) where they need to be, is accessible globally by default. A model such as User that is in /api/models/User.js can be accessed anywhere simply by doing User.findById(1). This Sails.JS feature can be configured to be turned off in the /config/globals.js.

Attributes

Here's an extensive list of all the attributes that you can use but I'd like to go over some basics. The most common types that you'll probably going to be using are string, datetime, email, boolean, integer, array and an object (I'll discuss this below when I go over creating relationships).

Let's say that we have a user registration system where we need to store some basic user information. You can define a User model such as:

model.exports = {  
    name: {
        type: 'string',
        required: true
    },
    lastLoggedIn: {
        type: 'datetime',
        defaultsTo: new Date()
    },
    favoriteNumbers: {
        type: 'array'
    },
    email: {
        type: 'email',
        unique: true
    }
}

I have included a variety of options so you can see what is possible and give you a sense of what that can look like.

The name property is set to a type of "string" which allows all character types that is set to required. The lastLoggedIn is of a "datetime" and defaults to current date if not provided. The favoriteNumbers property is set to an array which basically allows you to pass in array. Most of the property types are very basic and determined by your applications requirements including defaults, etc.

The email property in this case is of type "email" and is set to unique (meaning an error will be thrown if you insert the same email twice). Being an "email" type validates that this the string passed in is in the form of an email address but under the covers, it's still a "string" type.

If you're working against a NoSQL database backend, setting the property as unique isn't enough (the only thing that is unique is its id object, so it has to be configured in the /config/bootstrap.js to ensure that the database indeed does not allow duplicate email by (see code below).

// Bootstrap.JS
module.exports.bootstrap = function(cb) {  
  User.native(function(err, collection) {
    collection.ensureIndex('email', {
      unique: true
    }, function(err, result) {
      if (err) {
        sails.log.error(err);
      }
    });
  });

  // Trigger the callback to finish up the bootstrap process
  cb();

  _.extend(sails.hooks.http.app.locals, sails.config.http.locals);
};

Next up, I'd like to go over the database relationships as this is essential in more complex applications.

1-to-Many Relationship

NoSQL databases in general are document based so you can essentially store all data that pertains to that collection in a single document (nested data). There's also scenarios where having your data in separate documents might be a good idea depending on your application's needs. Storing data in different documents can be a good idea if you do a lot of "writes" but if your application is mostly "reads" then it makes more sense to go with a single document approach.

Since we're in discussion of relationships, we will work with an example that consists of multiple models/collections. I'll go over an example of 1-to-many relationship then further extend the example into the many-to-many relationship type.

For example:
A model User has UserTypes associated with it.

You can build out your models such as:

// User.JS
module.exports = {  
    identity: 'User',
    attributes: {
        name: {
            type: 'string'
        }
        userTypes: {
            collection: 'UserTypes',
            via: 'user'
        }
    }
}
// UserTypes.js
module.exports = {  
    identity: 'UserTypes',
    attributes: {
        user: {
            model: 'User'
        },
        userType: {
            type: 'string'
        }
    }
}

If you look at the defined models, User has an identity which is an optional property that allows you to set the name of the model to other than the default. You can set "User" to "foo" if you'd like to better describe the model. The attribute of userTypes. userTypes is specified as a collection of UserTypes model and points to the UserTypes via the user property. This defines a 1-many relationship between the User and UserTypes model.

On the other hand, UserTypes model simply just have the property of user which maps back to the User model. Using the example model above, the querying can be illustrated in the next section for ORM queries and how we can leverage this relationship.

Many-to-Many Relationship

Using the same models as above, we can define a many-to-many relationship using the concept of "followers" as an example. Twitter has this concept of allowing a user to follow other users and vice versa, hence the many-to-many relationship. Let's look at an example how that model relationship looks like when building the models.

// User.JS
module.exports = {  
    identity: 'User',
    attributes: {
        name: {
            type: 'string'
        }
        userTypes: {
            collection: 'UserTypes',
            via: 'user'
        },

        // Reference to user followers
        userFollowers: {
            collection: 'UserFollower',
            via: 'user'
        },

        // Reference to users that the user is following
        userFollowing: {
            collection: 'UserFollower',
            via: 'follower'
        }
    }
}
// UserFollower.JS
module.exports = {  
    identity: 'UserFollower',
    attributes: {
        user: {
            model: 'User'
        },

        follower: {
            model: 'User'
        }
    }
}

In the example above, I have extended the User model with 2 new properties namely userFollowers and userFollowing. The property definition are both set to the same collection UserFollower and uses the via object property that points to the UserFollower properties.

On the other hand, UserFollower have 2 properties as well that has a model specified as the User that points back to the User model.

In the next post (part 2), we will be exploring the ORM piece and re-use the examples in this post to perform basic and more advanced queries. Please let me know if you find this post useful. Feel free to comment as well for feedback and share it with others in your social media. Thanks for reading.

Thank you and keep shipping!

Comments

comments powered by Disqus