Search code examples
postgresqlpg-promise

How to refactor this POST code from MySQL to PostgreSQL?


I have this todo_list app built using:

  • Node.js
  • Express.js
  • EJS
  • MySQL

Choosing a database by following instructions from this Express website: https://expressjs.com/en/guide/database-integration.html#mysql https://expressjs.com/en/guide/database-integration.html#postgresql

I managed to make MySQL work with my todo_list app. But I'm having trouble refactoring the same CRUD (create) code for PostgreSQL use. Below is the working MySQL CRUD code and the unfinished PostgreSQL CRUD code for comparison. What am I doing wrong?

MySQL CRUD (create) code = works!

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

// _____________________________________________________________________________
// Add new list item - MySQL

let mysql = require('mysql');

let connection = mysql.createConnection({
  host: 'localhost',
  user: 'dbuser1',
  password: '12345',
  database: 'testdb1',
});


app.post("/", function(req, res) {

  const itemName = req.body.newItem;
  let data = { name: itemName };
  let sql = "INSERT INTO `todo_list` SET ?";

  let query = connection.query(sql, data, function(err, results) {
    if (err) throw err;
    res.redirect('/');
  });

});

PostgreSQL CRUD (create) code = doesn't work!

// .............................................................................
// Add new list item - PostgreSQL

// Loading and initializing the library without Initialization Options.
const pgp = require('pg-promise')();

const connection = {
  user     : 'pig1',
  password : '12345',
  host     : 'localhost',
  port     : '5432',
  database : 'todo_list'
};

// Database instance
const db = pgp(connection);


app.post("/", function(req, res) {

  const itemName = req.body.newItem;
  let data = { name: itemName };
  let sql = "INSERT INTO todo_list SET ?";

  db.any(sql, data)
  .then(results => {
    console.log(`Inserted data into database!`);
    console.log('DATA:', results);

    res.redirect('/');
  })
  .catch(error => {
    console.log('ERROR:', error);
  })
  .finally(db.$pool.end);
});

Solution

  • Thanks for the pointers! @vitaly-t @rabhi-salim

    I managed to make the CRUD (create) code work with PostgreSQL now.

    app.post("/", function(req, res) {
    
      const itemName = req.body.newItem;
      let data = { name: itemName };
    
      async function askStackOverflow() {
        try {
              await db.none('INSERT INTO todo_list(${this:name}) VALUES (${this:csv})', data);
    
              // --- SUCCESS ---
              console.log(``);
              console.log(`Inserted data into database!`);
              console.log(`DATA:`, insertedItem);
    
              res.redirect('/');
        } catch(error) {
             // --- ERROR ---
             console.log('ERROR:', error);
        }
      }
    
      (async () => {
        await askStackOverflow();
      })();
    
    });
    
    

    Extra reading material:

    Promises, Callback Hell, Async Await (ES7) https://www.digitalocean.com/community/tutorials/javascript-promises-for-dummies

    https://github.com/vitaly-t/pg-promise/wiki/Learn-by-Example#insert-with-result

    https://www.npmjs.com/package/pg-promise#named-parameters