2

I am learning Node JS with express and postgres and while I was making a CRUD app I got error like this when I execute my INSERT INTO statement.

(node:4998) UnhandledPromiseRejectionWarning: TypeError: Invalid Query Result Mask specified.
at Database.$query (/home/aabishkar/Documents/meanstack/node_modules/pg-promise/lib/query.js:121:25)
at Database.<anonymous> (/home/aabishkar/Documents/meanstack/node_modules/pg-promise/lib/query.js:259:23)
at config.$npm.connect.pool.then.db (/home/aabishkar/Documents/meanstack/node_modules/pg-promise/lib/database.js:326:42)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7) (node:4998) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3) (node:4998) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My code looks like this:

exports.dynamicadd =  function(req, res) {
  var name = req.body.name;
  var dob = req.body.dob;
  var gender = req.body.gender;
  var values = [name, gender, dob];
  console.log(values); //Up to here code is fine. It returns the value.
  //from here the error comes
  var sql = "INSERT INTO students (name, gender, dob) VALUES ?";
  db.query(sql, [values], function (err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
  res.redirect('/');
}

The DB is connected. Also for reference the following code works fine. The error comes when i try to insert the values dynamically.

//this codes works finely
exports.addlist = function(req, res) {
  qry = "INSERT INTO students (name, gender, dob) VALUES ('sdasda', 'male', '12-12-1999')";
  db.query(qry, function (err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
  res.redirect('/');
}

Thanks.

alexmac
  • 19,087
  • 7
  • 58
  • 69
  • 1
    Are you sure that `?` placeholders are valid for `pg-promise`? See [this answer](https://stackoverflow.com/a/29575963). – robertklep Nov 11 '18 at 15:41

1 Answers1

2

pg-promise returns a promise, it doesn't take a callback. You are using the library incorrectly. When values are the second parameter, then the third parameter is not supposed to be a callback, it is supposed to be a QueryResultMask

You should be using it is:

db.query(...)
 .then(r => console.log(r))
 .catch(e => console.log(e))

Check out this simple insert example

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100