gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'rows' of undefined

转载 作者:行者123 更新时间:2023-12-05 02:40:42 24 4
gpt4 key购买 nike

关注 Getting started with Postgres in your React app 时,在处理和导出 getMerchants、createMerchant 和 deleteMerchant 函数时,我收到此错误 -- 类型错误:无法读取未定义的属性“行”,这是怎么回事?这可能是我所缺少的非常小的东西。 getMerchants 和 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,
}

最佳答案

根据我的评论:

Second parameter for query is the query parameters, and not a callback function. Pass in [], if you do not have parameters. Other than that, your code looks largely redundant. You should follow proper async pattern that library offers, and not re-create all those useless promises...

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

然后像这样使用它:

const {rows} = await getMerchants();

关于javascript - 类型错误 : Cannot read property 'rows' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68414995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com