0

Hello I'm having trouble trying to figure out why I keep getting this long error message. I'm trying to create a simple signup function using Node.js, pg-promise with a postgreSQL Database.

(node:79941) UnhandledPromiseRejectionWarning: QueryResultError: 0
    at new QueryResultError (/Users/Documents/Login_Reg_app/node_modules/pg-promise/lib/errors/queryResult.js:131:24)
    at Query.ctx.db.client.query (/Users/Documents/Login_Reg_app/node_modules/pg-promise/lib/query.js:209:41)
    at Query.handleReadyForQuery (/Users/Documents/Login_Reg_app/node_modules/pg/lib/query.js:125:10)
    at Connection.<anonymous> (/Users/Documents/Login_Reg_app/node_modules/pg/lib/client.js:192:19)
    at Connection.emit (events.js:180:13)
    at Socket.<anonymous> (/Users/Documents/Login_Reg_app/node_modules/pg/lib/connection.js:125:12)
    at Socket.emit (events.js:180:13)
    at addChunk (_stream_readable.js:274:12)
    at readableAddChunk (_stream_readable.js:261:11)
    at Socket.Readable.push (_stream_readable.js:218:10)
(node:79941) 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: 2)
(node:79941) [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.
POST /signup - - ms - -

In my code I'm trying to check if the user's email is already registered in my database. If so, I want to alert that email is in use, else, proceed to registration of the website. If I comment out the first section of the code thats checks if the user's email is registered already, the registration code works just fine. And vice versa for the code that checks if the user email is already in the database. The problem is when I try to make both of them work together as one function. The code blows up ;( .

Please see my code

app.post('/', (req, res, next) => {

  const {
    first_name,
    last_name,
    user_name,
    email,
    password
  } = req.body;

  const created_on = date;

  const saltRounds = 10;

  //If user already exist in PostgreSQL Database

  db.one('SELECT user_id, first_name, last_name, email, user_name, password, created_on FROM users WHERE email = $1', [email])
    .then(user => {
      if (user) {
        return res.json({
            message: 'Email Already Exist' + email,
            user: user
          })
          .catch(error => {
            res.json({
              error: error,
              message: 'Unable to locate Email'
            })
            console.log(error);
          })
      } else {

        bcrypt.hash(password, saltRounds, (err, hash) => {

          //If  user never registered for website then following will execute

          db.none('INSERT INTO users(first_name, last_name, user_name, password, email,created_on) VALUES($1,$2,$3,$4,$5,$6)', [first_name, last_name, user_name, hash, email, created_on])
            .then(users => {
              res.json({
                message: 'User Created on ' + date,
                userInfo: req.body
              })
            })
            .catch(error => {
              res.json({
                error: error,
                message: 'Unable to Create User'
              })
              console.log(error);

            })
        })
      }
    })
})

I am fairly new to coding. I'm working on projects to improve my skill set. Any help would be greatly appreciated. Thank you in advance.

t.niese
  • 39,256
  • 9
  • 74
  • 101
AJH
  • 3
  • 1
  • 3
  • The `Unable to locate Email` handler needs to go in a `catch` on the `db.one('SELECT …')` promise, not be chained to `res.json(…)`. – Bergi Feb 03 '19 at 19:17
  • Btw I would recommend to [use `.then(…, …)` instead of `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572) here. – Bergi Feb 03 '19 at 19:19
  • Thank You Bergi I will this a try! When you stated that handler needs to go in a catch on db.one('SELECT ...') promise, not to be chained to res.json(...) Are you advising me to remove json and replace it with a console.log() instead? – AJH Feb 03 '19 at 21:22
  • No, it should stay there, if you want to send a response in the `if` branch. It just has nothing to do with promises, there should be no `.catch(…)` in the same statement. – Bergi Feb 03 '19 at 21:43
  • Okay I see now thank you. – AJH Feb 03 '19 at 21:47

1 Answers1

0

QueryResultError: 0 means that the query had no result, but the expected number of returned rows must not be zero. Using .one requires that the query returns exactly one row.

So your db.one('SELECT user_id, first_name, last_name, email, user_name, password, created_on FROM users WHERE email = $1', [email]) does not return a result for the email.

And it is a UnhandledPromiseRejectionWarning because you do not handle that case.

db.one('SELECT user_id, first_name, last_name, email, user_name, password, created_on FROM users WHERE email = $1', [email])
    .then(user => {
      if (user) {
        // ...
      } else {
        // ...
    } /*, function(err) {} */)
    // or .catch(function(err) {}) is missing here

But because of your if(user) your program logic expects that this query eitherreturns exactly one row or none, so you are looking for .oneOrNone(...) instead of .one(...). So your final code might look something like that:

db.oneOrNone('SELECT user_id, first_name, last_name, email, user_name, password, created_on FROM users WHERE email = $1', [email])
    .then(user => {
      if (user) {
        return res.json({
            message: 'Email Already Exist' + email,
            user: user
          })
      } else {

        bcrypt.hash(password, saltRounds, (err, hash) => {

          //If  user never registered for website then following will execute

          db.none('INSERT INTO users(first_name, last_name, user_name, password, email,created_on) VALUES($1,$2,$3,$4,$5,$6)', [first_name, last_name, user_name, hash, email, created_on])
            .then(users => {
              res.json({
                message: 'User Created on ' + date,
                userInfo: req.body
              })
            })
            .catch(error => {
              res.json({
                error: error,
                message: 'Unable to Create User'
              })
              console.log(error);

            })
        })
      }
    })
    .catch(error => {
      res.json({
        error: error,
        message: 'Unexpected error'
      })
      console.log(error);
    })
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • Thank You t.nise. I did move some things around however I'm still receiving an error. `There was a issue with this email QueryResultError { code: queryResultErrorCode.noData message: "No data returned from the query." received: 0 query: "SELECT user_id, first_name, last_name, email, user_name, password, created_on FROM users WHERE email = 'Pete100@email.com'" } POST /signup - - ms - -` – AJH Feb 03 '19 at 21:25