Home Logic Ubuntu (Linux) Blog

BocaJS: NodeJS + Postgres

NodeJS Query Function

Let's learn how to write a NodeJS query function!

Remember: In JavaScript, functions with a callback are asynchronous. NodeJS query functions must contain a callback! That makes them asynchronous. It's a good thing too! You don't want simple JavaScript calucations waiting on a database call, unless they have to.

Any code that is dependent on our query, will be called inside our query's callback. The code doesn't have to be physically written inside. To make your code easier to read, you can factor out code on seperate pages. You probably want to start creating your own library.

'use strict' - Helps avoid common coding mistakes (e.g. forgetting the var before i)
db - Connection variable saved in ./database/db.js
db.query - Query function

'use strict';
  if (err){
    // code to execute if there is an error
  else {
    // code to execute if no error
    var data = res.rows;

Code that executes, if there is an error.
Code that executes if the query is sucessful.
data - I set data equal to res.rows. The data response object contatins a lot of properties. res.rows contains returned data rows.

db.query's parameters
statement - This is a string variable that contains our SQL statement.
values - This is an array of paramaterized values (explained below). values is an optional parameter.
function(err,res) - This is the mandatory callback function. It is a function of err and res
function(err,res){} parameters
err - If your query returns an error, it is returned here.
res - If your query is sucessfully executed, the response is returned here.

Parameterized SQL Queries

We parameterized to prevent against SQL injection attacks.

SQL Injection

If your application includes a form with user input, a malicious user can use SQL statements to infiltrate your database. This might include stealing or deleting data.