2

I'm completely new to Node and Postgres and thought I would make my task a little easier by user Sails.js to build out my api for me. But I've search relentlessly for a single tutorial that walks you through all the steps. The official docs just show how to config the connection and also how to create a model. But how to get the model to call Postgresql and retrieve/update a table? Nothing. Every blog post just shows the connection.js setting and stops there. I also tried to find something on github thinking I would have working code to peruse and that just brings up Waterline docs. Any links that would be show the full process?

Thanks

user441058
  • 1,188
  • 1
  • 16
  • 32

2 Answers2

2

After creating your models and configuring connections.js to use your PostgreSQL database, do a sails console (usually sails lift, but we're using the console now to create some DB entries) in your app's root folder. You'll be prompted for a migration strategy you want to use for this particular lift. Select 3 - drop, and the database tables will automatically be created for you.

Let's say we have the following model, User, defined:

module.exports = {
    attributes: {
        name: {
            required: true,
            type: 'string'
        },
        age: 'int',
        email: {
            required: true,
            type: 'string'
        }
    }
}

From the sails console, you can now create a new user by entering the following:

User.create({name: 'John Johnson', age: 32, email: 'john.johnson@gmail.com'});

Then you can query for the created user as follows:

User.findOne({name: 'John Johnson'}).exec(console.log);

Or update him...

User.update({name: 'John Johnson'}, {age: 35});

or destroy him.

User.destroy({name: 'John Johnson'});

You can query and print all entries in a table with the following syntax, replacing Model with your model's name:

Model.find().exec(console.log);

All these queries are being made to your Postgres DB. If you need more info or something specific, feel free to ask - Waterline + Sails.js docs do cover most things pretty nicely, though.

Fissio
  • 3,748
  • 16
  • 31
  • Thanks! So when creating a new User model, Sails creates a global variable that lets you reference the User table. And then use the User global variable to call the Waterline functions for CRUD. Fantastic! This is the missing piece that isn't covered in any online articles for some reason (at least none found via a dozen Google searches). – user441058 Nov 19 '15 at 15:54
1

This tutorial shows you how to use Postgresql with sails.js http://articles.jeffjewiss.com/introduction-to-sails/

Ofer Herman
  • 3,018
  • 1
  • 20
  • 21