Cannot read properties of undefined (reading '3') Custom Database

*I am trying to use my database in the custom database section. It is a SQL server database, I managed to connect but I have a problem validating the password with the “rows[3]” and in the callback part likewise but with id, nickname and email. It seems to me that I am not being able to access the rows for some reason.

function login(email, password, callback) {
  const bcrypt = require('bcrypt');
  const sqlserver = require('tedious');

  const Connection = sqlserver.Connection;
  const Request = sqlserver.Request;
  const TYPES = sqlserver.TYPES;

  const connection = sqlserver.connect({
    server: '123.123.123,12',
    authentication: {
      type: 'default',
      options: {
        userName: 'test',
        password: 'Test!!!3',
      },
    },
    options: {
      port: 1234,
      database: 'BASE'
    },
  });

  const query = 'SELECT idUser, usrUsername, usrEmail, usrPassword FROM dbo.Users WHERE usrEmail = @Email';

  connection.on('debug', function (text) {
    console.log(text);
  }).on('errorMessage', function (text) {
    console.log(JSON.stringify(text, null, 2));
  }).on('infoMessage', function (text) {
    console.log(JSON.stringify(text, null, 2));
  });

  connection.on('connect', function (err) {
    if (err) return callback(err);

     const request = new Request(query, function (err, rowCount, rows) {
      if (err || rowCount < 1) return callback(err || new WrongUsernameOrPasswordError(email)); 
      
      bcrypt.compare(password, rows[0][3].value, function (err, isValid) {
        if (err || !isValid) return callback(err || new WrongUsernameOrPasswordError(email));

       const user = rows[0];
        
        callback(null, {
          user_id: rows[0][0].value,
          nickname: rows[0][1].value,
          email: rows[0][2].value
        });
      });
    });

    request.addParameter('Email', TYPES.VarChar, email);
    connection.execSql(request);
  });
}

1 Like

Facing the same issue.
Even though ‘rowCount’ is 1, the ‘rows’ seems to be empty.

I fix the problem.
The error was in the callback when returning the user_id. You have to make it a String.
Example:

 callback(null, {
          user_id: rows[0][0].value.toString(),
          nickname: rows[0][1].value,
          email: rows[0][2].value
        });