Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot read property 'rows' of undefined". I'm unsure what is causing this issue, as it seems like it could be a small oversight on my part. The error occurs specifically at the getMerchants function when trying to resolve(results.rows).

const Pool = require('pg').Pool
const pool = new Pool({
    user: 'my_user',
    host: 'localhost',
    database: 'my_database',
    password: 'root',
    port: 5432,
});

const getMerchants = () => {
    return new Promise(function(resolve, reject) {
        pool.query('SELECT * FROM userIds ORDER BY id ASC', (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(results.rows);
        })
    })
}
const createMerchant = (body) => {
    return new Promise(function(resolve, reject) {
        const { name, email } = body
        pool.query('INSERT INTO userIds (name, email) VALUES ($1, $2) RETURNING *', [name, email], (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(`A new merchant has been added added: ${results.rows[0]}`)
        })
    })
}
const deleteMerchant = () => {
    return new Promise(function(resolve, reject) {
        const id = parseInt(Request.params.id)
        pool.query('DELETE FROM userIds WHERE id = $1', [id], (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(`Merchant deleted with ID: ${id}`)
        })
    })
}

module.exports = {
    getMerchants,
    createMerchant,
    deleteMerchant,
}

Answer №1

In reference to my previous remark:

The second parameter in the query should consist of the query parameters, not a callback function. If you do not have any parameters, simply pass in []. Additionally, your code appears to be overly verbose. It is advisable to adhere to the asynchronous pattern provided by the library, rather than recreating unnecessary promises...

const retrieveUsers = () => pool.query('SELECT * FROM userIds ORDER BY id ASC');

Subsequently, you can utilize it in this manner:

const {rows} = await retrieveUsers();

Answer №2

Correct Code with a Password Issue

Although the code itself is correct, an error is triggered in the following scenarios:

  1. When no password is set at all, or
  2. When an incorrect password is entered. For instance, mistakenly using 'root' as a password instead of the correct 'postgres' for the user my_user. If everything else is functioning properly and only the password is incorrect, the same error will occur.

Here is the detailed error message:

myuser@mypc:~/project/node-postgres$ node index.js

App running on port 3001.
/home/myuser/myproject/node-postgres/merchant_model.js:17
      resolve(results.rows);
                      ^

TypeError: Cannot read property 'rows' of undefined
    at pool.query (/home/myuser/myproject/node-postgres/merchant_model.js:17:23)
    at PendingItem.connect [as callback] (/home/myuser/myproject/node-postgres/node_modules/pg-pool/index.js:363:16)
    at Client.client.connect [as _connectionCallback] (/home/myuser/myproject/node-postgres/node_modules/pg-pool/index.js:246:23)
    at Client._handleErrorWhileConnecting (/home/myuser/myproject/node-postgres/node_modules/pg/lib/client.js:305:19)
    at Client._handleErrorMessage (/home/myuser/myproject/node-postgres/node_modules/pg/lib/client.js:325:19)
    at Connection.emit (events.js:198:13)
    at parse (/home/myuser/myproject/node-postgres/node_modules/pg/lib/connection.js:114:12)
    at Parser.parse (/home/myuser/myproject/node-postgres/node_modules/pg-protocol/dist/parser.js:40:17)
    at Socket.stream.on (/home/myuser/myproject/node-postgres/node_modules/pg-protocol/dist/index.js:11:42)
    at Socket.emit (events.js:198:13)

To resolve this issue, refer to the guide at Getting started with Postgres in your React app: an end to end example for explanations on the code used. Additionally, for a deeper understanding, you can check How to quickly build an API using Node.js & PostgreSQL. Ensure PostgreSQL is installed and a "Merchant" table is created in the database following the guide.

If the error persists, verify the database role and password setup as per the guide. It is essential to have a password set for the my_user or postgres user. Adjust the pool settings in merchant_model.js accordingly.

Ensure the password prompt appears by running either:

psql -d my_database -U my_user

or:

psql -d my_database -U postgres

If password attempts fail, set a password for the respective user following a guide like Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails.

Resolution and Test

Once the password issue is resolved and the files are placed in the directory, execute node index.js in the project directory. If successful, you should see App running on port 3001. message indicating a backend setup at localhost:3001.

Following the frontend setup, running npm start displays the frontend at the specified port.

Ensure to follow the guide instructions thoroughly to troubleshoot and correct any password-related errors before establishing a successful connection.


PS: Code Quality Insights

Contrary to claims, the error isn't solely attributed to "bad coding." Utilizing the complete code from the guide's repository should function well, with errors stemming from password-related issues. It is suggested to adhere to the guide, implementing Promises for smoother execution.

Whether to apply the code with or without Promises is discretion. Following the guide and using Promises is advisable for efficient code execution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

How can you locate and emphasize specific text within various elements using JavaScript?

Created a script to highlight linked text in another HTML page. <p>Click <span class="f1"><a href="#myModal" data-reveal-id="myModal">here</a>/span></p> <div class="leftspread"> <p class="table-caption"& ...

Having trouble with the JOSN.parse function not functioning properly

Hello there, I'm currently attempting to extract data from a simple JSON string but encountering an error. The object I am trying to retrieve looks like this: { "heading" : "The movies", "box5" : "Click on icon to add text.", "box1" : "At the movies, ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Jquery is not displaying the background color of the progress bar

Greetings to all! I am currently working on implementing a progress bar for my website, but I am encountering an issue where the background-color is not displaying correctly on scroll. I would greatly appreciate any assistance with this matter. Below you c ...

Discovering the clicking actions on PDF elements within an HTML environment

I am currently working on developing a web application that involves rendering various pdf objects. My main goal is to be able to detect the position of a click inside the pdf container. However, it seems like the OnClick event is not functioning as expe ...

Unexpected outcomes arising from using nested arrays with jQuery validation plugin

I have been utilizing the jQuery validation plugin from . I am encountering an issue with validating a nested array "tax_percents[]" that is within another array. The validation seems to only work for the first value in the array, and even for the second f ...

Template file that generates a card displaying the articles "%> <%"

I've been diving into a YouTube tutorial on building a blog with node, MongoDB, and express. There are certain concepts that I'm finding tricky to grasp. <!--Creating the Article Cards--> <% article.forEach(article =>{ %& ...

Check to see if one string is beginning to resemble another string

Within an array, I have stored a set of keywords. When a user correctly types one of these keywords, the pass() function is executed. This validation occurs during each keystroke event (on key up), as I compare the user input to the items in the array. To ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

How to declare WinJS.xhr as a global variable in a Windows 8 Metro app

Currently, I am developing a Windows 8 Metro app and facing an issue with a hub page. The problem arises when pushing data dynamically from an XML API using two WinJs.xhr("url") calls; one for headings and the other for section datas. When merging both W ...

How to implement variables within the .map() function in JavaScript?

I am working on a map function where I need to pass in a variable as a Key to change the object item key to be based on that variable instead. For example, I want the obj.Salary below to actually represent the salary value when day equals "Day" instead o ...

divide a single item into several items depending on its attribute

data = {1-inputWidth : '30px' , 1-inputHeight: '30px', 1-color : 'red', 2-inputWidth : '20px' , 2-inputHeight: '10px', 2-color : 'blue', 3-inputWidth : '60px' , 3-inputHe ...

Utilizing data in mongoose: A beginner's guide

I have two database models: User and Conversations. The User model has the following schema: const userSchema = mongoose.Schema({ username: String, logo: String, ..... }) and the Conversation schema is as follows: const conversationSchema = mongo ...

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

IE 11 encountering issues with Date.parse returning NaN

Whenever I attempt to parse a date in Internet Explorer 11, it throws NaN at me. However, in Chrome and Firefox, I get the timestamp 1494559800000. Date.parse("5/12/2017 09:00 AM") The condition below is where things go wrong for me in IE 11. Is there an ...

Is there a way to prevent a form from automatically submitting once all inputs have been completed? (Using react-hook-form)

After creating a multi-step-form using shadcn, next, zod, and react-hook-form, I encountered an issue where the form is being submitted on step 3 instead of when clicking the submit button. form.tsx const form = useForm<Inputs>({ resolve ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Is there a way to visualize the prototype chain of a JavaScript object?

Consider the following code snippet: function a() {} function b() {} b.prototype = new a(); var b1 = new b(); It can be observed that a has been incorporated into the prototype chain of b. This demonstrates that: b1 is an instance of b b1 is an instance ...

Chrome hanging after AJAX delete operation has been executed

After conducting a same-origin AJAX delete using jQuery, any subsequent calls made by the same client to the server are getting stuck. The specific issue is outlined below. Can you please review and let me know if there's something incorrect, as this ...