How to use mysql, mongodb, and postgresql in SailsJS

About this topic, you might think, why would you blog something that is already well said in the documentation. Well, turns out that i just wanna completing my previous blog topics, Create RESTful API in less than 5 minutes with sailsjs and Add API Authentication in SailsJS, which they are related each others.

One of great things or i'm more likely call it the magic things about SailsJS, is the waterline that can combine between ORM (Object Relational Mapper) and ODM (Object Document Mapper) in one code, so its mean, you could use your favorite database (mysql, mongodb or postgresql) but still using the same code and by default sailsjs use a sails-disk as local database for the development.

Since it's not so hard, so i would just go straight forward to the main steps, and i'm assume that you are using our awesomeAPI project from previous tutorial, so all we need to do are install and change the adapters (awesomeAPI/config/connections).

How to setup MySQL
  1. Install your mysql database on your machine, and make sure it working and running, then create a database called awesomeAPI.
  2. Install the mysql adapter
    npm install sails-mysql
  3. Add/edit the folowing code:someMysqlServer: { adapter: 'sails-mysql', host: 'localhost', user: 'root', password: '', database: 'awesomeAPI' },
    1. Then edit config/connections.js and this
      connection: 'someMysqlServer'
How to setup MongoDB
  1. Install your mongodb database, you can follow the steps here and you can use any GUI apps, like robomongo.
  2. Install the adapter by run this code
    npm install sails-mongo
  3. Add/edit the folowing code:someMongodbServer: { adapter: 'sails-mongo', host: 'localhost', port: 27017, // user: 'username', // password: 'password', // database: 'yourmongodbnamehere' },
  4. Then edit config/connections.js and this
    connection: 'someMongodbServer'
How to setup PostgreSQL
  1. Install postgresql, if you are using mac you could use
  2. Install the adapter
    npm install sails-postgresql
  3. Add/edit the folowing code:somePostgresqlServer: { adapter: 'sails-postgresql', host: 'localhost', user: '< username >', password: '', database: '< db name >' }
  4. Then edit config/connections.js and this
    connection: 'somePostgresqlServer'

Choose one of the adapters above then run sails lift, if there is no error its mean you're ready to go, and to make you sure, register your data http://localhost:1337/register and then check your data on your database.

Now you're ready to make a real application from it.


Cendekia P Putra

< Software Developer /> | @cendekiapp |

Jakarta, Indonesia