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
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.